Iterator over HashMap in Java

后端 未结 9 1657
醉酒成梦
醉酒成梦 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:46

    Several problems here:

    • You probably don't use the correct iterator class. As others said, use import java.util.Iterator
    • If you want to use Map.Entry entry = (Map.Entry) iter.next(); then you need to use hm.entrySet().iterator(), not hm.keySet().iterator(). Either you iterate on the keys, or on the entries.

提交回复
热议问题