我在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/