简体   繁体   中英

HashMap and HashTable giving different Execution Result

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.

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM