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使用比较简单,根据应用场景使用就好!!!