如何从HashMap中获取Object?

时间:2018-05-23 16:54:14

标签: java object 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
        }
    }

5 个答案:

答案 0 :(得分:3)

您在方法签名中声明了类型约束,但在方法体中,您没有利用类型约束。

您正在使用的是与使用HashMap&lt;对象,对象&gt;。这就是编译错误的原因。

正确代码:

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

答案 1 :(得分:2)

更改此行:

Iterator it = e.entrySet().iterator();

为:

Iterator<Entry<Direction, Exit>> it = e.entrySet().iterator();

答案 2 :(得分:1)

以下是我如何迭代HashMap

中的每个值
HashMap<Directive, Exit> tempHashMap = new HashMap<>();
        for(Directive directive:tempHashMap.keySet()){
            Exit tempExit = tempHashMap.get(directive);
            //do what you want with the exit
        }

答案 3 :(得分:0)

您正在使用类似列表的HashMap。这不是一个非常有效的清单。

取而代之的是

 Object value = map.get(key);

它将非常有效地跳过不在密钥下面的项目。

public void setExits(HashMap<Direction, Exit> exits, Direction direction){
    this.exits = e.get(direction);
}

答案 4 :(得分:0)

您错过的是Map.Entry的泛型。

在我看来,就像你试图遍历地图的所有条目一样,你可能会发现for循环更容易。

for(Map.Entry<Direction, Exit> entry : e.entrySet()) {
    Direction dir = entry.value();
    //do stuff
} 
相关问题