【问题标题】:Error when adding element to ListOfMap in Java在 Java 中将元素添加到 ListOfMap 时出错
【发布时间】:2015-02-01 03:24:18
【问题描述】:

我在 java 中使用 Map List,但遇到了麻烦。我用:

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,}}

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

【问题讨论】:

    标签: java arraylist map


    【解决方案1】:

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

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

    进入

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

    【讨论】:

      【解决方案2】:

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

      否则,您也只需清除 List 内的 HashMap,因为它们引用的是同一个对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-22
        • 1970-01-01
        • 1970-01-01
        • 2015-02-07
        • 1970-01-01
        相关资源
        最近更新 更多