We all know that Set(Except their such implementation) doesn't guarantee of iteration ordering .So i tried to make sure this with below sample code .
public static void main(String[] args) throws InterruptedException {
Map<String,String> lMap=new HashMap<String, String>();
lMap.put("A", "A");
lMap.put("B", "B");
lMap.put("C", "C");
lMap.put("D", "D");
lMap.put("E", "E");
lMap.put("F", "F");
lMap.put("G", "G");
lMap.put("H", "H");
lMap.put("I", "I");
lMap.put("J", "J");
lMap.put("K", "K");
lMap.put("L", "L");
for(int i=0;i<10000;i++){
Thread.sleep(100);
Set<Entry<String, String>> entrYset=lMap.entrySet();
for(Map.Entry<String, String> e:entrYset){
System.out.println(e.getKey()+" , "+e.getValue());
}
System.out.println("******************************************************");
}
}
I executed above code many times and found that it is printing records in order.
My question is if java claims HashMap is unordered then why this records are printing in order . If someone can give me reason with example that would be great.
The order is the same each time because the hash code of string doesn’t change and you are inserting the in the same order. Hashmap is deterministic, so if you create the same hashmap and insert things in the same order, you’ll always get a consistent ordering.
Hashmap doesn’t give any guarantee that this ordering will remain consistent. If you insert more items the the ordering may completely change as the hash table is rebuilt.