我正在尝试简单的 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/