We observed below mentioned program which uses hash map still gives the output in ascending order of the keys.
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class SampleProgram {
public static void main(String[] args) {
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(100, "A");
hmap.put(107, "C");
hmap.put(101, "Z");
hmap.put(106, "Y");
hmap.put(104, "P");
hmap.put(105, "Q");
hmap.put(108, "R");
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry me = (Map.Entry) iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
}
}
As i read in java documents, that hash map does not return any order. But we observed that in the above mentioned program it is sorting the keys and returning the output.But at the same time we used following data set to cross verify that time it is not sorting.So, what is the reason ?
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class SampleProgram {
public static void main(String[] args) {
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(30, "A");
hmap.put(5, "C");
hmap.put(76, "Z");
hmap.put(100, "Y");
hmap.put(90, "P");
hmap.put(34, "Q");
hmap.put(23, "R");
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry me = (Map.Entry) iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
}
}