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!

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I didn't reuse the lists and works perfectly now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.