
本教程操作环境:windows7系统、java10版,DELL G3电脑。
1.AbstractMap
AbstractMap是一个抽象类,在具体的 Map 的实现类和接口之间定义的一层抽象,为了就是服务一些用的函数。
AbstractMap
1 2 | public abstract class AbstractMap<K,V> implements Map<K,V> {
}
|
2.HashMap
HashMap 是一个最常用的Map,它根据键的HashCode 值存储数据,根据键可以直接获取它的值,具有很快的访问速度。HashMap最多只允许一条记录的键为Null;允许多条记录的值为 Null;HashMap不支持线程的同步,即任一时刻可以有多个线程同时写HashMap;可能会导致数据的不一致。如果需要同步,可以用 Collections的synchronizedMap方法使HashMap具有同步的能力。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | transient Node<K,V>[] table;
static final int hash(Object key) {
int h;
return (key == null ) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
public V put(K key, V value) {
return putVal(hash(key), key, value, false , true );
}
TreeMap
TreeMap 是一个基于红黑树的有序的 Map ,继承自 AbstractMap 抽象类,实现了 NavigableMap 接口,这个接口又继承了 SortedMap 。
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null ){
...
}
|
3.TreeMap
TreeMap 是一个基于红黑树的有序的 Map ,实现了 NavigableMap 接口,这个接口又继承了 SortedMap 。
1 2 3 4 5 6 7 8 | final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null ){
...
}
|
4.map架构

以上就是java中常见的两种map,在结尾处我们分享了map的框架给大家,对其他map感兴趣的可以自行查阅资料。更多Java学习指路:js教程