我需要一个可以具有任何类型值的Map。因此,我尝试使用 HashMap 。但是,如果尝试从映射中获取值,则IDE会指出类型不匹配。
这是我代码的一部分:
Map<String, Object> state1 = new HashMap<>();
state1.put("location", exit1);
state1.put("direction", direction);
state1.put("number", 0);
Deque<Map> q = new ArrayDeque<>();
q.add(state1);
List<Integer> numbers = new ArrayList<>();
while (!q.isEmpty()) {
Map<String, Object> state = q.poll();
Pair location = state.get("location");
在此部分之前已经定义了变量 exit1 , direction ,因此您可以忽略它。另外,您不必关心此部分下面的代码。
我的IDE表示行Map<String, Object> state = q.poll();
具有不兼容的类型-需要 Pair ,但是找到了 Object 。如何使它兼容?
我正在处理一个只能运行一个文件的问题,因此我无法实现新类。
答案 0 :(得分:2)
...
Pair location = null;
if(state.get("location") instanceof Pair){
Pair location = (Pair)state.get("location");
}
else{
...
}
答案 1 :(得分:0)
您可以这样指定通用类型:
Deque<Map<String, Object>> q = new ArrayDeque<>();