0

I want add HashMap of student to ArrayList of students at each iteration but the output in the student HashMap is different with student_list, specifically the value of "id" i is not changing instead it always print the upper bound of the loop termination value. Below is the code. I need to know where i got it wrong.

I suppose to get unique id for each student on the final list as it appears on the individual student details but the result is otherwise. even if I print inside the loop, the final list is the same with below result.

HashMap<String, Object> student = new HashMap<String, Object>();
ArrayList<HashMap<String, Object>> students_list = new 
ArrayList<HashMap<String, Object>>();
for (int i=0; i<3; i++) {
    student.put("Name", "James");
    student.put("id", i);
    student.put("Level", "Two");
    System.out.println("The student details are  "+student);
    students_list.add(student);
}   
System.out.println("List of students list is "+students_list.toString());

Output:

The student details are  {Level=Two, id=0, Name=James}
The student details are  {Level=Two, id=1, Name=James}
The student details are  {Level=Two, id=2, Name=James}
List of students is      [{Level=Two, id=2, Name=James}, {Level=Two, 
id=2, Name=James}, {Level=Two, id=2, Name=James}]
GBlodgett
  • 12,704
  • 4
  • 31
  • 45
sirbakura
  • 11
  • 2
  • You are adding the same reference to `student` over and over again, so it will contain the same object n times. Move the line: `HashMap student = new HashMap();` inside the loop and you'll get the desired output – GBlodgett Jan 10 '19 at 03:04

2 Answers2

1

You are altering the same object "student" in each iteration and putting it to a hash map with a new key. Links to the object will be stored in HashMap buckets but they will still point to the same object.

Re-create the object in each iteration

public static void main(String[] args) {
    List<Map<String, Object>> students = IntStream.range(0, 3).mapToObj(index -> {
        Map<String, Object> student = new HashMap<>();
        student.put("Name", "James");
        student.put("id", index);
        student.put("Level", "Two");
        return student;
    }).collect(Collectors.toList());
    System.out.println(students);
}
Azee
  • 1,809
  • 17
  • 23
0

You're only constructing one student; move down the first line so that it's inside the for loop:

ArrayList<HashMap<String, Object>> students_list = new 
ArrayList<HashMap<String, Object>>();
for (int i=0; i<3; i++) {
    HashMap<String, Object> student = new HashMap<String, Object>();
    student.put("Name", "James");
    student.put("id", i);
    student.put("Level", "Two");
    System.out.println("The student details are  "+student);
    students_list.add(student);
}

System.out.println("List of students list is "+students_list.toString());
dtanabe
  • 1,611
  • 9
  • 18