一. 结论
- Map的常用实现类Hashtable、TreeMap、HashMap、LinkedHashMap的keySet()方法获取key的顺序:
- LinkedHashMap.keySet()得到的Set是有序的;
- 其他三个得到的Set都是无序的。
二. 代码实现
public class MapKeySetTest {
private Hashtable<String, String> hashtable = new Hashtable<>();
private TreeMap<String, String> treeMap = new TreeMap<>();
private HashMap<String, String> hashMap = new HashMap<>();
private LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
public void initData(){
for(int i=0; i<31; i++){
hashtable.put(String.valueOf(i),i+"");
treeMap.put(String.valueOf(i),i+"");
hashMap.put(String.valueOf(i),i+"");
linkedHashMap.put(String.valueOf(i),i+"");
}
}
public static void main(String[] args) {
MapKeySetTest test = new MapKeySetTest();
test.initData();
System.out.println("HashTable:"+test.hashtable.keySet());
System.out.println("TreeMap:"+test.treeMap.keySet());
System.out.println("HashMap:"+test.hashMap.keySet());
System.out.println("LinkedHashMap:"+test.linkedHashMap.keySet());
}
}
HashTable:[30, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 29, 8, 28, 7, 27, 6, 26, 5, 25, 4, 24, 3, 23, 2, 22, 1, 21, 0, 20]
TreeMap:[0, 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3, 30, 4, 5, 6, 7, 8, 9]
HashMap:[22, 23, 24, 25, 26, 27, 28, 29, 30, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 21]
LinkedHashMap:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]