-1

Basically, I know the difference between HashMap and HashTable.

I was trying to understand the difference between them by actually coding it out.

Here is my Main Method in Java

System.out.println("HashMap");
HashMap <String , String> map = new HashMap<String, String>();
map.put("A", "Hello");
map.put("B", "World");
Set<String> set = map.keySet();
map.put("C", "YoYo");
Iterator<String> itr = set.iterator();
while(itr.hasNext())
{
    String temp = itr.next();
    System.out.println(temp +" value: "+ map.get(temp));
}

System.out.println("HashTable");
Hashtable<String ,  String> table = new Hashtable<>();
table.put("A", "Hello");
table.put("B", "World");
Set<String> set2 = table.keySet();
table.put("C", "YoYo");
Iterator<String> itr2 = set2.iterator();
while(itr2.hasNext())
{
    String temp = itr2.next();
    System.out.println(temp +" value: "+ table.get(temp));   
}

Here is the output I got:

HashMap    
A value: Hello    
B value: World    
C value: YoYo    
HashTable    
A value: Hello    
C value: YoYo    
B value: World 

Why two different results.
Isn't it sorted the same way in both cases?
Thank you.

Jay Patel
  • 1,266
  • 6
  • 20
  • 38
  • what i can see from behavior of `HashMap` and `HashTable ` is that new item is added at the end of list in `HashMap` but in case of `HashTable` it is after 1st element. so i can say `HashMap` append the element while `HashTable` inserting the element. – Rustam Oct 08 '15 at 08:11
  • Curious: what were you expecting to prove here? If you are looking to prove to yourself what the difference is between the two classes, why would you expect exactly the same results? – Gimby Oct 08 '15 at 08:23

2 Answers2

5

HashMap and HashTable don't guarantee order. If you want order you have to use LinkedHashMap, It you want it to be sorted you have to use TreeMap.

shazin
  • 21,379
  • 3
  • 54
  • 71
1

This is because iteration order is not guaranteed for both classes.

You may want to take a look of the below: is the Java HashMap keySet() iteration order consistent?

Community
  • 1
  • 1
Porz
  • 183
  • 3
  • 15