简体   繁体   English

如何从 Hashmap 中获取值<String, Object> ?

[英]How can I get a value from Hashmap<String, Object>?

I need a Map that can have values of any type.我需要一个可以具有任何类型值的 Map。 So I've tried to use HashMap .所以我尝试使用HashMap However, if I try to get a value from the map, the IDE says that the type doesn't match.但是,如果我尝试从地图中获取值,IDE 会说该类型不匹配。

This is a part of my code with the matter:这是我的代码的一部分:

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

The variables exit1 , direction are already defined before this part, so you may ignore about that.变量exit1direction已经在这部分之前定义,所以你可以忽略它。 Also, you don't have to care about the code below this part.此外,您不必关心这部分下面的代码。

My IDE says that the line Map<String, Object> state = q.poll();我的 IDE 说Map<String, Object> state = q.poll(); has incompatible types — Pair is required but Object is found.具有不兼容的类型 — 需要Pair但找到Object How can I make this compatible?我怎样才能使它兼容?

I am working on a problem that can run only one file, so I can't implement a new class.我正在解决一个只能运行一个文件的问题,所以我无法实现一个新类。

...
Pair location = null;
if(state.get("location") instanceof Pair){
  Pair location = (Pair)state.get("location");
}
else{
...
}

您可以像这样指定泛型类型:

Deque<Map<String, Object>> q = new ArrayDeque<>();

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

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