Reputation: 7141
I am trying to store integers in a data structure with a String as the key, an example of what im storing is:
key: "Name1", Int: 123
key: "Name2", Int: 124
I want to be able to insert entries so that they are ordered alphabetically for purposes of easy printing to screen.
So far ive been using:
Dictionary<String,Integer> x = new Hashtable<String,Integer>();
x.put("Name1",123);
x.put("Name2",124);
Enumeration<String> e;
String key;
for(e=x.keys(); e.hasMoreElements();){
key=e.nextElement();
System.out.println(key + ": " + x.get(key));
}
This Outputs:
Name2: 124
Name1: 123
Why aren't these in alphabetical order? Is there an alternative to Dictionary that I should know about?
Upvotes: 1
Views: 5109
Reputation: 359786
Unless otherwise stated, maps/hashmaps/hashtables/dictionaries/etc. don't have any defined sort ordering. A TreeMap<String, Integer>
should work for your purposes; it implements the SortedMap<K, V>
interface.
That said, I'm not necessarily convinced you should be picking a data structure just because it makes printing easier.
Side note: Dictionary
and Hashtable
are legacy classes which exist primarily for backwards compatibility. New code should generally prefer Map
and HashMap
for general-purpose key-value data structures.
Upvotes: 4