Click here to Skip to main content
15,895,256 members
Articles / Programming Languages / Java / Java SE

Implementing Ordering in a Hashtable

Rate me:
Please Sign up or sign in to vote.
4.25/5 (16 votes)
20 Jun 20026 min read 115.5K   296   11  
A Hashtable provides a key-value lookup functionality. Hashtable in java.util.Hashtable is not guaranteed to Enumerate (or Iterate) keys in the same order as they were put in. This article explains how to implement ordering in a Hashtable.
import java.util.*;


/* 	A class to test the Ordering functionality of OrderedHashtable.java
	Elements retreived from OrderedHashtable are in same order as they
	were put in. This behaviour is not guaranteed in Hashtable.
	@author Animesh Srivastava
*/

public class Test
{
	public static void main(String args[])
	{
		OrderedHashtable aOrdData = new OrderedHashtable();
		Hashtable aHashData = new Hashtable();

		int num=10;

		System.out.println("Putting in "+ num +" values in order 0 to "+num);
		for (int i=0;i<num;i++)
		{
			aHashData.put(new Integer(i),new Integer(i*i));
			aOrdData.put(new Integer(i),new Integer(i*i));
		}


		{
			System.out.println("Retreiving from Hashtable - not guaranteed to be in sequence.");
			Enumeration e = aHashData.keys();
			while(e.hasMoreElements())
				System.out.println(aHashData.get(e.nextElement()));
		}


		{
			System.out.println("Retreiving from OrderedHashtable - guaranteed to be in sequence.");
			Enumeration e = aOrdData.enumerateKeys();
			while(e.hasMoreElements())
				System.out.println(aOrdData.get(e.nextElement()));
		}


	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
C/C++ Win32 developer, working on Java! Wink | ;)

Comments and Discussions