代码之家  ›  专栏  ›  技术社区  ›  Fabian Zbinden

如何从HashMap中获取对象?

  •  -1
  • Fabian Zbinden  · 技术社区  · 8 年前

    我试图从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 回复  |  直到 8 年前
        1
  •  3
  •   LHA    8 年前

    您正在方法签名中声明类型约束,但在方法体中,您没有利用使用类型约束的任何优势。

    您所做的与使用HashMap类似<对象,对象>。这就是编译错误的原因。

    正确代码:

    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
        }
    }
    
        2
  •  2
  •   Vishrant    8 年前

    更改此行:

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

    致:

    Iterator<Entry<Direction, Exit>> it = e.entrySet().iterator();
    
        3
  •  1
  •   Sam Orozco    8 年前

    下面是我如何迭代 HashMap

    HashMap<Directive, Exit> tempHashMap = new HashMap<>();
            for(Directive directive:tempHashMap.keySet()){
                Exit tempExit = tempHashMap.get(directive);
                //do what you want with the exit
            }
    
        4
  •  0
  •   Edwin Buck    8 年前

    你正在使用 HashMap 就像一张清单。这不是一个非常有效的列表。

    而是

     Object value = map.get(key);
    

    它会非常高效地跳过不在键下的项。

    public void setExits(HashMap<Direction, Exit> exits, Direction direction){
        this.exits = e.get(direction);
    }
    
        5
  •  0
  •   MartinByers    8 年前

    你错过的是地图的泛型。进入

    在我看来,好像你正在尝试循环地图的所有条目,你可能会找到一个更简单的for循环。

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