如何定义List >?

问题描述 投票:0回答:1

我正在制作一种需要返回列表的方法。

private List<Map<String, Object>> mapDO(List<dO> dOList) {
        List<Map<String, Object>> oMapList = new ArrayList<>();
        Map<String, Object> oMap = new HashMap<>();

        for (int i = 0; i < dO.size(); i++) {
            ordersMap.clear();
            ordersMap.put("description", dOList.get(i).getDescription());
            ordersMap.put("size", dOList.get(i).getSize());
            System.out.println(i);
            System.out.println(ordersMap);
            ordersMapList.add(ordersMap);
            System.out.println(ordersMapList);
        }

        return ordersMapList;
    }

问题是:Arraylist stores the reference and does not copy/create new objects. If you change the stored object reference, it will be reflected in the arrayList as well.上面的代码的输出是:

0
{size=One size, description=Product 1}
[{size=One size, description=Product 1}]
1
{size=One size, description=Product 2}
[{size=One size, description=Product 2}, {size=One size, description=Product 2}]
2
{size=One size, description=Product 3}
[{size=One size, description=Product 3}, {size=One size, description=Product 3}, {size=One size, description=Product 3}]

我尝试使用.set(index,element)属性,因为要解决此问题,我需要使用setter,但似乎找不到找到初始化oMapList的方法。我尝试了以下操作,但所有操作均会出错:

  1. [List<Map<String, Object>> oMapList = new ArrayList<>(dOList.size());但这给集提供了容量,实际上没有作用。
  2. [List<Map<String, Object>> oMapList = Arrays.asList(new Map<String, Object>[dOList.size()];给出通用数组创建错误。

还有其他解决方法吗?

java object arraylist initialization size
1个回答
0
投票

不确定我是否真的理解了这个问题,但是看一下代码,似乎您想要一个Map列表,但是您只向列表中添加了一个没有意义的Map。

也许您想要的是这个:

private List<Map<String, Object>> mapDO(List<dO> dOList) {
    List<Map<String, Object>> ordersMapList = new ArrayList<>();


    for (int i = 0; i < dO.size(); i++) {
        Map<String, Object> ordersMap = new HashMap<>();
        ordersMap.put("description", dOList.get(i).getDescription());
        ordersMap.put("size", dOList.get(i).getSize());
        System.out.println(i);
        System.out.println(ordersMap);
        ordersMapList.add(ordersMap);
        System.out.println(ordersMapList);
    }

    return ordersMapList;
}

在每次迭代中创建一个新地图,并将其添加到列表中。

© www.soinside.com 2019 - 2024. All rights reserved.