简体   繁体   中英

Java data structure sorted by key

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM