[英]How do I get Object out of HashMap?
我試圖從HashMap中獲取一個對象並從該對象中調用一個方法。 但是出於獲取對象的考慮,我得到了一個普通的java.lang.Object
。
public void setExits(HashMap<Direction, Exit> e){
this.exits = e;
Iterator it = e.entrySet().iterator();
while (it.hasNext()) {
Map.Entry exits = (Map.Entry) it.next();
Exit r = exits.getValue(); //HERE I GET ERROR
}
}
您在方法簽名中聲明類型約束,但是在方法主體中,您沒有利用類型約束的任何優勢。
您正在執行的操作類似於使用HashMap <Object,Object>。 這就是為什么編譯錯誤。
正確的代碼:
public void setExits(HashMap<Direction, Exit> e){
this.exits = e;
Iterator<Map.Entry<Direction, Exit>> it = e.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Direction, Exit> entry = it.next();
Exit r = entry.getValue(); // OK
}
}
更改此行:
Iterator it = e.entrySet().iterator();
至:
Iterator<Entry<Direction, Exit>> it = e.entrySet().iterator();
這就是我如何迭代HashMap
每個值的方法
HashMap<Directive, Exit> tempHashMap = new HashMap<>();
for(Directive directive:tempHashMap.keySet()){
Exit tempExit = tempHashMap.get(directive);
//do what you want with the exit
}
您正在使用像列表這樣的HashMap
。 這不是一個非常有效的列表。
相反做
Object value = map.get(key);
它將非常有效地跳過鍵下的項目。
public void setExits(HashMap<Direction, Exit> exits, Direction direction){
this.exits = e.get(direction);
}
您錯過的是Map.Entry的泛型。
在我看來,好像您試圖遍歷地圖的所有條目一樣,您可能會發現for循環更容易。
for(Map.Entry<Direction, Exit> entry : e.entrySet()) {
Direction dir = entry.value();
//do stuff
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.