简体   繁体   中英

How do I get Object out of HashMap?

Im trying to get an object out of a HashMap and call a method from this object. But insted of getting the object, I get a normal 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
        }
    }

You are declaring type constraints in the method signature but in the method body you are not taking any advantage of using the type constraints.

What you are doing is similar to you are using HashMap< Object, Object >. That is why compile error.

Correct Code:

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

Change this line:

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

to:

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

Here is how I might iterate every value in a HashMap

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

You are using a HashMap like a list. It's not a very effective list.

Instead do

 Object value = map.get(key);

And it will skip the items that aren't under the key, very efficiently.

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

What you have missed is the generics for the Map.Entry.

It looks to me as though you are trying to loop over all the entries of the map, you might find a for loop easier.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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