Meaningless Drivel is fun!*
The moose likes Java in General and the fly likes ordering of elements in Hashtable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "ordering of elements in Hashtable" Watch "ordering of elements in Hashtable" New topic

ordering of elements in Hashtable

Gowrishankar Mudaliar
Ranch Hand

Joined: Oct 20, 2001
Posts: 39

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();



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.
Gowrishankar Mudaliar
Ranch Hand

Joined: Oct 20, 2001
Posts: 39
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

Joined: Oct 20, 2001
Posts: 39
I tried with LinkedHashMap and it worked.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
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.



Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: ordering of elements in Hashtable
Similar Threads
collections framework
Hashtable, put and get sanity check
HashMap: keySet() and values order
Clarification regarding HashMap
help please on puts and gets?