devxlogo

Maintaining the Order of Inserting and Retrieving Java Objects Using Hashtable

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.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist