簡體   English   中英

如何從 Hashmap 中獲取值<String, Object> ?

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

我需要一個可以具有任何類型值的 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");

變量exit1direction已經在這部分之前定義,所以你可以忽略它。 此外,您不必關心這部分下面的代碼。

我的 IDE 說Map<String, Object> state = q.poll(); 具有不兼容的類型 — 需要Pair但找到Object 我怎樣才能使它兼容?

我正在解決一個只能運行一個文件的問題,所以我無法實現一個新類。

...
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