1

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?

2
  • You're looking for a TreeMap Commented Jun 22, 2013 at 19:26
  • 1
    possible duplicate of Java Ordered Map Commented Jun 22, 2013 at 19:27

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You should mention the SortedMap and NavigableMap interfaces, which do specify an ordering.
Printing isnt the only reason, i need it to overwrite duplicate entries too, im fairly sure most of the maps do that though
@clairharrison correct - any correct implementation of Map will prohibit duplicate keys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.