有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java,从映射迭代器获取对象,然后调用方法?

我有一张地图,里面有一些物体,比如说苹果。我目前有一个迭代器,但我似乎只能调用getKey和getValue。getValue似乎返回实际Apple对象的内存地址,但我希望能够执行Apple a=Map。进入getValue()

我似乎只能得到密钥和内存地址:s

Iterator it = ApplesMap.entrySet().iterator();     
while (it.hasNext()) {         
    Map.Entry entries = (Map.Entry)it.next();         
    System.out.println(entries.getKey() + " = " + entries.getValue());
    //Apple a = entries.getValue(); 
} 

共 (4) 个答案

  1. # 1 楼答案

    使用泛型:

    Map<String, Apple> map = ....;
    

    如果你需要钥匙:

    for (Map.Entry<String, Apple> entry : map.entrySet()) {..}
    

    如果你不需要钥匙:

    for (Apple apple : map.values()) {..}
    

    因为您在其中一条评论中有一个子问题:在引擎盖下,for each循环使用Iterator。每个Iterable类都有资格使用for-each循环。但是,您不必为操作迭代器而烦恼——它是为您自动操作的。如果你想调用Iterator,那么remove()仍然很有用

  2. # 2 楼答案

    试着设定价值

    Apple a = (Apple) entries.getValue();
    a.beDelicious();
    
  3. # 3 楼答案

    这是古老的密码。使用泛型和for each循环

    Map<String, Apple> map = // create map here
    for(Map.Entry<String, Apple> entry : map.entrySet()){
        Apple thisIsAnApple = entry.getValue();
        String andThisIsTheKeyThatLinksToIt = entry.getKey();
    }
    

    顺便说一句:

    • 如果你只是想要钥匙,就用 map.keySet()
    • 如果您只是想要这些值,请使用 map.values()
    • 只有在需要时才使用map.entrySet() 完全映射
  4. # 4 楼答案

    如果您使用的是JDK 6,可以这样尝试:

    for (Apple apple : applesMap.values())
    {
        // process apple here.
    }