I inserted some data into a Java Hashtable. If I read the data from the Hashtable it doesn’t come back in the same order that I inserted it in. How do I get the ordered data from the Hashtable?
I use the following code to get the values from the hashtable:
// Get a set of the entries
Set set = hsUpdateValues.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.print(
"Key : " + me.getKey()
+ ", Value: " + me.getValue()
);
}
If you want an order-preserving map, you should use
LinkedHashMap:Note that this is usually compared with
HashMaprather thanHashtable– I don’t know of an order-preserving equivalent toHashtable; the latter isn’t usually used these days anyway (just asArrayListis usually used in preference toVector).I’ve assumed you want insertion order rather than key-sorted order. If you want the latter, use
TreeMap.