HashMap
1.允許鍵、值都是null(鍵只允許一個,值可以多個)
2.鍵重複,就直接執行值覆蓋
3.順序是不確定的
4.超過初始容量,將以二倍遞增,大數據情況下內存開銷大
5.不支持線程同步,如果需要做同步,需要使用Collections的synchronizedMap方法使HashMap具有同步的能力
6.讀寫速度和容量有關
HashTable
與hashMap基本等價,區別:不允許允許鍵、值都是null
LinkedHashMap
1.在HashMap基礎上保證插入數據的一致性(插入順序)
2. 允許鍵、值都是null , 如果鍵重複,就直接執行值覆蓋
3. 讀寫速度和數據有關
TreeMap
在JDK1.8之前或者之後,都直接或間接的實現了SortedMap(排序)接口,把插入的數據默認按照鍵值得升序排列,也可以指定比較器(Comparator)
TreeMap使用
1.按照鍵的升序、降序排序
import java.util.*;
import java.util.Comparator;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
TreeMap<String, User> treeMap = new TreeMap<String, User>(
new Comparator<String>() {
public int compare(String obj1, String obj2) {
// 降序排序
// return obj2.compareTo(obj1);
// 升序排序
return obj1.compareTo(obj2);
}
});
treeMap.put("c", new User(12, "44"));
treeMap.put("a", new User(15, "42"));
treeMap.put("d", new User(10, "48"));
treeMap.put("b", new User(19, "86"));
//獲取所有的鍵
Set<String> keySet = treeMap.keySet();
for (String key :
keySet) {
//鍵值排序結果
System.out.println("key == " + key + " value = " + treeMap.get(key));
}
}
}
輸出:
key == a value = User{age=15, score=42}
key == b value = User{age=19, score=86}
key == c value = User{age=12, score=44}
key == d value = User{age=10, score=48}
2.自定義比較器,比較值
import java.util.*;
import java.util.Map.Entry;
public class Main2 {
public static void main(String[] args) {
TreeMap<String, User> treeMap = new TreeMap<String, User>(
new Comparator<String>() {
public int compare(String obj1, String obj2) {
// 降序排序
// return obj2.compareTo(obj1);
// 升序排序
return obj1.compareTo(obj2);
}
});
treeMap.put("c", new User(12, "44"));
treeMap.put("a", new User(15, "42"));
treeMap.put("d", new User(10, "48"));
treeMap.put("b", new User(19, "86"));
//這裏將map.entrySet()轉換成list
List<Entry<String,User>> list = new ArrayList<Entry<String,User>>(treeMap.entrySet());
//然後通過比較器來實現排序
Collections.sort(list,new Comparator<Entry<String,User>>() {
//升序排序
public int compare(Entry<String, User> o1,
Entry<String, User> o2) {
return o1.getValue().getScore().compareTo(o2.getValue().getScore());
}
});
for(Entry<String,User> mapping:list){
//鍵值排序結果
System.out.println("key == " + mapping + " value = " + mapping.getValue().toString());
}
}
}
輸出:
key == a=User{age=15, score=42} value = User{age=15, score=42}
key == c=User{age=12, score=44} value = User{age=12, score=44}
key == d=User{age=10, score=48} value = User{age=10, score=48}
key == b=User{age=19, score=86} value = User{age=19, score=86}
HashMap、HashTable、LinkedHashMap使用比較簡單,根據應用場景使用就好!!!