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

标签 java arraylist dictionary

我在java中使用 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,}}

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

最佳答案

您使用相同的映射来存储所有元素,但在每次迭代开始时,您调用 item.clear(); ,这会删除映射内以前存储的元素。您应该做的是创建新的独立 map ,而不是重复使用旧 map ,因此请更改

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

进入

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

关于java - 在Java中向ListOfMap添加元素时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27273853/

相关文章:

java - ArrayDeque vs ArrayList 实现堆栈

java - 将字符串与我的 ArrayList 进行比较

python - 在 python 上使用字典

Jquery:图像 map 区域上的鼠标悬停事件

java - 玩! Framework FakeApplication - 它实际上做了什么?

java - 使用 tc 服务器设置 kerberos 的问题

java - Oracle 在关闭结果集后不删除游标

java - ArrayList .contains() 有时为真,有时为假

dictionary - 如何将数据集转换为存储库内的字典。我在 Foundry 中使用 pyspark

java - JSONParser getResourceAsStream