不同Map获取的KeySet()顺序问题
Map的常用实现类Hashtable、TreeMap、HashMap、LinkedHashMap的keySet()方法获取key的顺序:
- LinkedHashMap.keySet()得到的Set是有序的;
- 其他三个得到的Set都是无序的。
package com.nsk666.map;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.TreeMap;
public class MapTest {
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) {
MapTest test = new MapTest();
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());
}
}