You are getting a keySet iterator on the HashMap and expecting to iterate over entries.
Correct code:
HashMap hm = new HashMap();
hm.put(0, "zero");
hm.put(1, "one");
//Here we get the keyset iterator not the Entry iterator
Iterator iter = (Iterator) hm.keySet().iterator();
while(iter.hasNext()) {
//iterator's next() return an Integer that is the key
Integer key = (Integer) iter.next();
//already have the key, now get the value using get() method
System.out.println(key + " - " + hm.get(key));
}
Iterating over a HashMap using EntrySet:
HashMap hm = new HashMap();
hm.put(0, "zero");
hm.put(1, "one");
//Here we get the iterator on the entrySet
Iterator iter = (Iterator) hm.entrySet().iterator();
//Traversing using iterator on entry set
while (iter.hasNext()) {
Entry<Integer,String> entry = (Entry<Integer,String>) iter.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
System.out.println();
//Iterating using for-each construct on Entry Set
Set<Entry<Integer, String>> entrySet = hm.entrySet();
for (Entry<Integer, String> entry : entrySet) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Look at the section -Traversing Through a HashMap in the below link. java-collection-internal-hashmap and Traversing through HashMap