[英]Java Fill nested HashMap
I have a problem.我有个问题。 I created the following object:
我创建了以下 object:
HashMap<String, HashMap<String, HashMap<Integer, ArrayList<Slope>>>>
usedSlopeList = new HashMap<>();
Then I have the following ArrayList<Slope>
:然后我有以下
ArrayList<Slope>
:
ArrayList<Slope> tempSlopeList = Slope.getSlopeList(
agent, key, slope, startDateTimeWithExtraCandles);
But when I want to fill the usedSlopeList
like this:但是当我想像这样填充
usedSlopeList
时:
usedSlopeList.put("15m",
new HashMap<String, HashMap<Integer, ArrayList<Slope>>>()
.put("EMA15", new HashMap<Integer, ArrayList<Slope>>()
.put(15, tempSlopeList)));
Unfortunately this gives me the error:不幸的是,这给了我错误:
Required type: HashMap<Integer,java.util.ArrayList<com.company.models.Slope>>
Provided: ArrayList<Slope,
But I don't see why this is wrong... Can someone help me?但我不明白为什么这是错误的......有人可以帮助我吗?
Map::put
returns value while a map is expected. Map::put
返回值,而 map 是预期的。
That is, new HashMap<Integer, ArrayList<Slope>>().put(15, tempSlopeList)
returns ArrayList<Slope>
and so on.即
new HashMap<Integer, ArrayList<Slope>>().put(15, tempSlopeList)
返回ArrayList<Slope>
等等。
The following code using Map.of
available since Java 9 works fine:以下代码使用
Map.of
自 Java 9 起可用:
usedSlopeList.put("15m", new HashMap<>(Map.of("EMA15", new HashMap<>(Map.of(15, tempSlopeList)))));
Update A cleaner solution not requiring Java 9 could be to implement a generic helper method which creates an instance of a HashMap
and populates it with the given key/value:更新不需要 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: Output:
{15m={EMA15={15=[]}}}
You used the new HashMap().put() as the second parameter in your code, which causes the issue.您使用 new HashMap().put() 作为代码中的第二个参数,这会导致问题。
HashMap().put is not a builder method; HashMap().put不是构建器方法; it doesn't return the hashmap.
它不返回 hashmap。 It returns the previous value associated with the key, which in your case is an ArrayList.
它返回与键关联的先前值,在您的情况下是 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, add the object and than try to add it. 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 然后尝试添加它。 Anyway i think you should reconsider your design.
无论如何,我认为你应该重新考虑你的设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.