简体   繁体   English

按键排序的Java数据结构

[英]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: 我试图将整数存储在一个数据结构中,以String作为键,im存储的一个例子是:

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. 除非另有说明,否则map / hashmaps / hashtables / dictionaries / etc. don't have any defined sort ordering. 没有任何已定义的排序顺序。 A TreeMap<String, Integer> should work for your purposes; TreeMap<String, Integer>应该适合您的目的; it implements the SortedMap<K, V> interface. 它实现了SortedMap<K, V>接口。

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. 附注: DictionaryHashtable是遗留类,主要用于向后兼容。 New code should generally prefer Map and HashMap for general-purpose key-value data structures. 对于通用键值数据结构,新代码通常更喜欢MapHashMap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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