Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Jul 27, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Maintaining the Order of Inserting and Retrieving Java Objects Using Hashtable

We know that using Hashtable we can put and get the java objects relatively fast. But Hashtable does not maintain the order in which you add and retrieve the objects. Using a combination of hashtables we can accomplish this. With the following tip you can maintain the order.
 java.util.Hashtable hash = new java.util.Hashtable();
for(int i = 0; i < 3 ; i++) {
	Hashtable subHash = new Hashtable();
String name = "name"+i;
String value= "Foo"+i;
	subHash.put(name, value);
hash.put(new Integer(i), subHash);
When you retrieve it, and if you want to retrieve the second item, which might be value associated with "name1" then you can have code:
for(int i=0; i < hash.size(); i++){
	Hashtable subHash = (Hashtable)hash.get(new Integer(i));
	if(subHash != null){
		String retValue =null;
retValue = (String)subHash.get("name1")
If(retValue != null)
	return retValue;
Also when we loop through the objects we can retrieve all the objects in the order in which they were inserted.
Raghu Donepudi
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date