HashMap 是非线程安全的,无序的。
LinkedHashMap、TreeMap 是有序的
public static void main(String[] args) {
System.out.println("hashmap:根据哈希值取出");
Map<String, String> hashMap = new HashMap<>();
hashMap.put("a", "textA");
hashMap.put("b", "textB");
hashMap.put("c", "textC");
hashMap.put("1", "text1");
Iterator<Entry<String, String>> it = hashMap.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, String> e = it.next();
System.out.println("Key: " + e.getKey() + "; Value: " + e.getValue());
}
System.out.println("LinkedHashMap:取出的顺序跟放进去的顺序是一样的");
Map<String,String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("a", "textA");
linkedHashMap.put("b", "textB");
linkedHashMap.put("c", "textC");
linkedHashMap.put("1", "text1");
it = linkedHashMap.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, String> e = it.next();
System.out.println("Key:"+e.getKey()+"; Value:"+e.getValue());
}
System.out.println("TreeMap:字典排序(根据的是Key不是Value)底层结构是: 红黑树");
//
Map<String,String> treeMap = new TreeMap<>();
treeMap.put("a", "textA1");
treeMap.put("b", "textB");
treeMap.put("c", "textC");
treeMap.put("1", "textA2");
it = treeMap.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, String> e = it.next();
System.out.println("Key:"+e.getKey()+"; Value:"+e.getValue());
}
}
hashmap:根据哈希值取出
Key: a; Value: textA
Key: 1; Value: text1
Key: b; Value: textB
Key: c; Value: textC
LinkedHashMap:取出的顺序跟放进去的顺序是一样的
Key:a; Value:textA
Key:b; Value:textB
Key:c; Value:textC
Key:1; Value:text1
TreeMap:字典排序(根据的是Key不是Value)底层结构是: 红黑树
Key:1; Value:textA2
Key:a; Value:textA1
Key:b; Value:textB
Key:c; Value:textC