有 Java 编程相关的问题?

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

迭代器Java如何迭代映射<String,Device>

我有一个自定义映射,其中Device是名为Device的类的实例

devices = new HashMap<String, Device>();

我尝试了StackOverflow上建议的几个迭代器和for循环,但它们似乎都产生了错误,我不知道为什么

示例错误:

enter image description here

enter image description here


共 (4) 个答案

  1. # 1 楼答案

    看起来devices的声明不正确。应该是:

    Map<String, Device> devices;
    

    不是原始的(“擦除的”)类型,Map。现代编译器应该为您提供使用原始类型的警告。注意编译器警告

  2. # 2 楼答案

    你能试试这个吗:

    HashMap<String, Device> devices = new HashMap<String, Device>();
    
    // do stuff to load devices
    
    Device currentDevice;
    for (String key : devices.keySet()) {
    
        currentDevice = devices.get(key);
        // do stuff with current device
    
    }
    
  3. # 3 楼答案

    在第一个场景中,你只需给出

    对于(Map.Entry:devices.entrySet()){

    这就足够了,你不需要施放地图。条目(字符串、设备)在那里。在第二种情况下,当您从条目中获取值时,它会返回对象值,因此您需要将其转换为特定实例。所以你必须付出

    设备设备=(设备)对。getValue()

  4. # 4 楼答案

    有三种方法可以迭代地图 1) 使用For Each循环对条目进行迭代。 2) 使用For Each循环对键或值进行迭代。 3) 使用迭代器进行迭代。(为此,可以使用泛型或不使用泛型进行迭代)

        Map map = new HashMap();
    Iterator entries = map.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry entry = (Map.Entry) entries.next();
        Integer key = (Integer)entry.getKey();
        Integer value = (Integer)entry.getValue();
        System.out.println("Key = " + key + ", Value = " + value);
    }