java - 我的 ArrayList 正在覆盖以前的数据

标签 java arraylist

我正在尝试简单的 ArrayList 示例来解决其他代码的一些问题,但这个简单的代码给出了错误的输出。

我创建了一个 Hashmap 的 Arraylist,将 3 个键/值对放入该 Hashmap 中,然后将该 Hashmap 放入 ArrayList 中,如下所示,

public class SortData {

    public static void main (String [] args){

    ArrayList<HashMap<String, String>> myArrayList = new ArrayList<HashMap<String,String>>();

    HashMap<String, String> myHashMap = new HashMap<String, String>();


        myHashMap.put("title",  "first Title");
        myHashMap.put("date",   "This is date");
        myHashMap.put("number", "5");

        myArrayList.add(0, myHashMap);

但是当我尝试在数组列表中添加更多数据时,

import java.util.ArrayList;
import java.util.HashMap;

public class SortData {

    public static void main (String [] args){

    ArrayList<HashMap<String, String>> myArrayList = new ArrayList<HashMap<String,String>>();

    HashMap<String, String> myHashMap = new HashMap<String, String>();


        myHashMap.put("title",  "first Title");
        myHashMap.put("date",   "This is date");
        myHashMap.put("number", "5");

        myArrayList.add(0, myHashMap);


        myHashMap.put("title",  "Second Title");
        myHashMap.put("date",   "This is 2nd date");
        myHashMap.put("number", "2");

        myArrayList.add(1, myHashMap);

        myHashMap.put("title",  "Third Title");
        myHashMap.put("date",   "This is 3rd date");
        myHashMap.put("number", "7");

        myArrayList.add(2, myHashMap);


        System.out.println(myArrayList.get(0)+"");
        System.out.println(myArrayList.get(1)+"");
        System.out.println(myArrayList.get(2)+"");


    }


}

输出是,

{title=Third Title, number=7, date=This is 3rd date}
{title=Third Title, number=7, date=This is 3rd date}
{title=Third Title, number=7, date=This is 3rd date}

为什么ArrayList中之前的值会被覆盖? 两种我都试过了,

myArrayList.add(Hashmap())myArrayList.add(int index, Hashmap()) 但输出是相同的

最佳答案

ArrayList 添加对您添加的 HashMap 的引用,而不是副本。您将相同的 HashMap 添加到 ArrayList 3 次。每次添加后,您都会通过更多 put 调用来更改内容,这会覆盖预先存在的值,因为 key 相同。

myArrayList[ o , o , o ]
             |   |   |
             +---+   |
             |       |
             +-------+
             |
             v
             myHashMap

要添加不同的内容,请每次添加不同的HashMap,通过运行

myHashMap = new HashMap<String, String>();

在前 2 个添加之后。

myArrayList[ o , o , o ]
             |   |   +-> HashMap
             |   |   
             |   +-----> HashMap
             |
             +---------> HashMap

关于java - 我的 ArrayList 正在覆盖以前的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27866080/

相关文章:

Python:列表超出范围

java - 双链表中删除方法内部的未知 for 循环?

java - Websphere 上的 Cron 调度程序的 org.springframework.jndi.JndiLookupFailureException

java - 什么时候需要将 java 中的十六进制文字转换为(字节)?

java - 如何显示ArrayList每小时的数据?

java - 无法比较子类中ArrayList的大小

Java 7 oracle 不支持 TLSv1.2

Java数组没有保持初始化

java - 如何在Java中声明多个数组列表

java - 将链表转换为 ArrayList