Java填充嵌套HashMap



我有一个问题。我创建了以下对象:

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返回

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);    

输出:

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

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

HashMap()。Put不是一个构造器方法;它不返回hashmap。它返回与键相关联的前一个值,在你的例子中是一个ArrayList。

您有一个映射,它期望字符串作为键,hashmap作为值,但是put()方法不返回hashmap,它返回一个V对象(<K,>),这就是为什么您应该单独创建hashmap,添加对象,然后尝试添加它。无论如何,我认为你应该重新考虑你的设计。

最新更新