Iterator over HashMap in Java

后端 未结 9 1668
醉酒成梦
醉酒成梦 2021-02-07 05:43

I tried to iterate over hashmap in Java, which should be a fairly easy thing to do. However, the following code gives me some problems:

HashMap hm = new HashMap(         


        
9条回答
  •  时光说笑
    2021-02-07 06:39

    You should really use generics and the enhanced for loop for this:

    Map hm = new HashMap<>();
    hm.put(0, "zero");
    hm.put(1, "one");
    
    for (Integer key : hm.keySet()) {
        System.out.println(key);
        System.out.println(hm.get(key));
    }
    

    http://ideone.com/sx3F0K

    Or the entrySet() version:

    Map hm = new HashMap<>();
    hm.put(0, "zero");
    hm.put(1, "one");
    
    for (Map.Entry e : hm.entrySet()) {
        System.out.println(e.getKey());
        System.out.println(e.getValue());
    }
    

提交回复
热议问题