【发布时间】:2019-01-09 21:52:37
【问题描述】:
我想在每次迭代时将学生的HashMap 添加到学生的ArrayList,但学生HashMap 的输出与student_list 不同,特别是“id”i 的值并没有改变而是它总是打印循环终止值的上限。下面是代码。我需要知道我哪里弄错了。
我想为最终列表中的每个学生获取唯一的 ID,因为它显示在单个学生的详细信息中,但结果并非如此。即使我在循环内打印,最终列表与以下结果相同。
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());
输出:
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}]
【问题讨论】:
-
您一遍又一遍地添加对
student的相同引用,因此它将包含相同的对象n 次。在循环内移动行:HashMap<String, Object> student = new HashMap<String, Object>();,您将获得所需的输出
标签: java for-loop arraylist collections hashmap