繁体   English   中英

Java 填充嵌套 HashMap

[英]Java Fill nested HashMap

我有个问题。 我创建了以下 object:

HashMap<String, HashMap<String, HashMap<Integer, ArrayList<Slope>>>>
     usedSlopeList = new HashMap<>();

然后我有以下ArrayList<Slope>

ArrayList<Slope> tempSlopeList = Slope.getSlopeList(
    agent, key, slope, startDateTimeWithExtraCandles);

但是当我想像这样填充usedSlopeList时:

usedSlopeList.put("15m", 
new HashMap<String, HashMap<Integer, ArrayList<Slope>>>()
    .put("EMA15", new HashMap<Integer, ArrayList<Slope>>()
    .put(15, tempSlopeList)));

不幸的是,这给了我错误:

Required type: HashMap<Integer,java.util.ArrayList<com.company.models.Slope>>
Provided: ArrayList<Slope,

但我不明白为什么这是错误的......有人可以帮助我吗?

Map::put返回,而 map 是预期的。

new HashMap<Integer, ArrayList<Slope>>().put(15, tempSlopeList)返回ArrayList<Slope>等等。

以下代码使用Map.of自 Java 9 起可用:

usedSlopeList.put("15m", new HashMap<>(Map.of("EMA15", new HashMap<>(Map.of(15, tempSlopeList)))));

更新不需要 Java 9 的更清洁的解决方案可能是实现一个通用的帮助方法,该方法创建一个HashMap的实例并用给定的键/值填充它:

static <K, V> HashMap<K, V> fillMap(K key, V val) {
    HashMap<K, V> map = new HashMap<>();
    map.put(key, val);
    return map;
}

ArrayList<Slope> tempSlopeList = new ArrayList<>(Collections.emptyList());
HashMap<String, HashMap<String, HashMap<Integer, ArrayList<Slope>>>>
     usedSlopeList2 = fillMap("15m", 
                          fillMap("EMA15", 
                              fillMap(15, tempSlopeList)
                          )
                      );
    
System.out.println(usedSlopeList2);    

Output:

{15m={EMA15={15=[]}}}

您使用 new HashMap().put() 作为代码中的第二个参数,这会导致问题。

HashMap().put不是构建器方法; 它不返回 hashmap。 它返回与键关联的先前值,在您的情况下是 ArrayList。

You have a map, which expects a string as key and a hashmap as value, but put() method doesn't return a hashmap, it return an V object(<K, V>), that is why you should create hashmap separately ,添加 object 然后尝试添加它。 无论如何,我认为你应该重新考虑你的设计。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM