0

I'm trying to set HashMap values in java whilst trying to reuse an arrayList. I hadn't worked with HashMaps before and am still get my head around this, so please bear with my limited knowledge.

Class Student:

public class Student {

    private static int id = 0;
    private String name;
    private String surname;
    private Map<Subject, List<Grade>> grades;
    private List<Absence> absences;
}

grades setter:

public void setGrades(Map<Subject, List<Nota>> grades) {
    this.grades = grades;
}

Class Subject:

public class Subject {

    private String name;
}

Class Grade:

public class Grade {

    private Term term;
    private String letter;
}

Main program:

Subject subject = new Subject("History");
Map<Subject, List<Grade>> gradeMap = new HashMap<Subject, List<Grade>>();  
        List <Grade> grades = new ArrayList<Grade>();

grades.add(new Grade(Term.FIRST_TERM, 'A'));
grades.add(new Grade(Term.SECOND_TERM, 'F'));
grades.add(new Grade(Term.THIRD_TERM, 'B'));
gradeMap.put(subject, grades);

student1.setGrades(gradeMap);

Test printing the keys and values :

for(Map.Entry<Subject, List<Grade>> t :student1.getGrades().entrySet()){
             Subject key = t.getKey();
             for (Grade grade : t.getValue()) {
                 System.out.println(key.getName() + " - " + grade.getNumber());
            }        
        }

But whenever i try to reutilize the ArrayList, since there are many students whose grades need setting, I lose all data in my student1 instance

grades.clear();

If I try printing to console now the output is empty:

for(Map.Entry<Subject, List<Grade>> t :student1.getGrades().entrySet()){
             Subject key = t.getKey();
             for (Grade grade : t.getValue()) {
                 System.out.println(key.getName() + " - " + grade.getNumber());
            }        
        }

I would really appreciate any comments and suggestions on this, clearly I must be doing something wrong but I don't know what :D

Thanks in advance!

Juan M
  • 4,063
  • 4
  • 19
  • 28

1 Answers1

4

What you put in the map is a reference to that same list you still have. It didn't create a copy of it (as Java doesn't do such things), what you hold is still that same list that's in the map. If you want a new one you need to create it manually:

grades = new ArrayList<>();

And than the only reference to the one with Student1 record will indeed be in that map.

See Is Java "pass-by-reference" or "pass-by-value"? for more details.

Deltharis
  • 2,320
  • 1
  • 18
  • 29