【问题标题】:Add HashMap to ArrayList in For-loop Iteration [duplicate]在 For 循环迭代中将 HashMap 添加到 ArrayList [重复]
【发布时间】: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&lt;String, Object&gt; student = new HashMap&lt;String, Object&gt;();,您将获得所需的输出

标签: java for-loop arraylist collections hashmap


【解决方案1】:

你只构建了一个student;向下移动第一行,使其位于 for 循环内:

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());

【讨论】:

    【解决方案2】:

    您在每次迭代中更改同一个对象“学生”,并将其放入带有新键的哈希映射中。指向对象的链接将存储在 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-06
      • 2013-10-20
      • 2021-07-31
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      相关资源
      最近更新 更多