在Java中向ListOfMap添加元素时出错

时间:2014-12-03 14:11:45

标签: java arraylist map

我在java中使用Map of Map但是我遇到了麻烦。我用:

Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); ArrayList<Map<String,AttributeValue>> maps = new ArrayList<Map<String,AttributeValue>>();

我使用CSVReader读取文件并在ListOfMap中存储值

CSVReader reader = new CSVReader(new FileReader("data1.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
    // nextLine[] is an array of values from the line
    item.clear();
    item.put("Id", new AttributeValue().withN(nextLine[0]));
    item.put("Name", new AttributeValue().withS(nextLine[1]));

    System.out.println("Item:"+item); // I try printing item
    maps.add(item);
    }

结果是:

    Item:{Id={N: 0,}, Name={S: goGOv,}}
    Item:{Id={N: 1,}, Name={S: TBlGD,}}
    Item:{Id={N: 2,}, Name={S: OtXuw,}}
    ...
    Item:{Id={N: 999,}, Name={S: QAMzc,}}
    Item:{Id={N: 1000,}, Name={S: PumAq,}}

但是当我从这个列表中打印一些元素时

System.out.println(" "+maps.get(i)); // I tried i from 0-1000

它总是只显示1个输出

{Id={N: 1000,}, Name={S: PumAq,}}

所以任何人都可以告诉我我错在哪里。 谢谢,

2 个答案:

答案 0 :(得分:1)

您正在使用相同的地图来存储所有元素,但是在每次迭代开始时,您调用item.clear();来删除映射中先前存储的元素。你应该做的是创建一个新的,单独的地图而不是重用旧地图,所以改变

item.clear();//don't reuse previously filled map because it still is the same map

item = new HashMap<>();//use separate map

答案 1 :(得分:0)

您继续使用相同的Map对象。这些是持久性对象。您必须实例化一个新的HashMap(),而不是在现有的HashMap上调用clear()。

否则你只需清除List里面的HashMap,因为它们引用同一个对象。