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}]
答案 0 :(得分:0)
您仅构造一个$LATEST
;向下移动第一行,使其位于for循环内:
student
答案 1 :(得分:0)
您将在每次迭代中更改相同的对象“学生”,并将其放入具有新键的哈希图中。指向该对象的链接将存储在HashMap存储桶中,但它们仍将指向同一对象。
在每次迭代中重新创建对象
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);
}