2 Replies Latest reply: Feb 26, 2009 11:45 PM by 752426 RSS

    How to sort elements in Hashtable.

    807588
      I am adding elements in sorted order in Hashtable. But when I iterate through the Hashtable using 'Enumeration' on the keys the the elements are not fetched in sorted order. I want to retrieve the keys in sorted order. How can we fetch the keys on sorted order?
      import java.util.* ;
      
      public class temp
      {
      
           public static void main(String [] abc) 
           {
      
                Hashtable hashList = new Hashtable();
                hashList.put("1","One");
                hashList.put("2","Two");
                hashList.put("33","Three");
                hashList.put("44","Four");
      
           Enumeration keys = hashList.keys();
      
           while(keys.hasMoreElements() )
                     {
                          System.out.println("Key: " + keys.nextElement());
                     }
           }
      }
      
      Output for this is -
      
      Key: 2
      Key: 1
      Key: 33
      Key: 44