Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does HashTable maintains the insertion order?

Tags:

The following code gives me the output in the same order of insertion. I read the javadoc and they did not even talk about the insertion order. Can someone help me to get the right information.

import java.util.*;  public class hash {  public static void main(String[] args) {      String str[] = { "japan",             "usa",             "japan",             "russia",             "usa",             "japan",             "japan",             "australia"};     int len = 8;     Hashtable ht = new Hashtable();     int i = 0;     while (i < len) {          String c = str[i];         System.out.println("c :" + c);         Integer intg = (Integer) ht.get(c);          if (intg == null)             ht.put(c, new Integer(1));         else             ht.put(c, new Integer(intg.intValue() + 1));          i++;     }      Enumeration k = ht.keys();      while (k.hasMoreElements()) {         String key = (String) k.nextElement();         System.out.println(key + " > " + ht.get(key));     } } } 
like image 988
wayfare Avatar asked Jun 19 '11 23:06

wayfare


2 Answers

No, it does not. To preserve insertion order, instead use java.util.LinkedHashMap (javadoc).

Also, HashMap is now preferred over Hashtable, because Hashtable has unnecessary concurrency overhead. (See Differences between HashMap and Hashtable?.)

like image 198
Mechanical snail Avatar answered Sep 27 '22 22:09

Mechanical snail


no, it does not. it only knows the "hash" order. if you reorder the strings, you will find they still appear in the same order from the hashtable.

like image 23
jcomeau_ictx Avatar answered Sep 27 '22 20:09

jcomeau_ictx