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}]