Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ordering of elements in Hashtable

 
Gowrishankar Mudaliar
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Is there any way i can retrieve keys and values in the same order that i put. I am not sure why hashtable.keys() does not give the keys back in the same order and i dont understand the order in which it returns the keys.

Consider the example program.

import java.util.Hashtable;

public class hashtest
{
public static void main(String c_strAr[])
{
Hashtable c_ht= new Hashtable();

c_ht.put("one","1");
c_ht.put("two","2");
c_ht.put("three","3");

System.out.println(c_ht);
}
}

The output is : {two=2, one=1, three=3}

It should have been..:{one=1, two=2, three=3}

Is there a way i can get the values back in the same order that i inserted ..?

Thanks in Advance.
Gowri
 
Gowrishankar Mudaliar
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried TreeMap, but i get the output as {one=1, three=3, two=2}

I don't need this too. Is there any other way?
 
Gowrishankar Mudaliar
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried with LinkedHashMap and it worked.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I strongly advise you to find a tutorial on the Collections Framework. Any such tutorial worth its salt will explain the differences between different classes that implement the same interface. You should also familiarize yourself with the Java API documentation. First find the link to the documentation for the version of Java that you are using. Then to find the docs for a particular class, scroll the upper left frame down until you find the package that contains the class. In this case, all the Collection classes are in the java.util package. When you click on the package link, it loads the names of the classes in that package in the bottom left frame. Scroll until you find a class you want to learn more about, such as HashMap (notice the upper case M). When you click on the class name, the documentation for that class is loaded in the main frame on the right. This page gives a in-depth description of the class as well as a list of all non-private methods and fields. The list at the top gives links to more detailed descriptions further down the page. Learning to navigate this documentation is a crucial skill when programming Java, imo. It will help you find the differences between similar classes, such as those that you encountered above.

HTH

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic