Java Map详解 底层原理

原文地址

Map详解 底层原理

Map

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
将键映射到值的对象。映射不能包含重复的键; 每个键最多可以映射到一个值。

public interface Map<K,V>
并没有继承Collection接口

Map主要函数

 
int size();
boolean isEmpty();
boolean containsKey(Object key);
boolean containsValue(Object value);
V get(Object key);
V remove(Object key);
void putAll(Map<? extends K, ? extends V> m);
void clear();
Set<K> keySet();
Collection<V> values();
//返回Map中所包含的键值所对应的Set集合
Set<Map.Entry<K, V>> entrySet();
//内部的Entry,每个集合的元素都是Entry对象
K getKey();//返回Entry的Key值
V getValue();//返回Entry的value值
V setValue(V value);//设置Entry的value值

Map中主要的实现类

一、HashMap

 
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
//默认内存大小,必须是2的幂
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大内存
static final int MAXIMUM_CAPACITY = 1 << 30;
//哈希节点
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}
// 计算key的hash值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//hash表
transient Node<K,V>[] table;
//通过计算hash值来来比较key
//过去value
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//获取流程:
//根据hash值获取hash表中对应的值
//--如果first.key是否也key对应。对应则返回
//--如果不同则存在hash冲突
//----因为1.8之后加入红黑树,hash冲突先判断是否已经转化为红黑树,否则还是链表的形式,查找到返回即可。
inal Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
//重点关注 添加值
// 先查找hash是否存在,不存在直接添加进表即可
//-存在,则判断是否key是否已经存在了
//---判断是否转化为了红黑树,是 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//-----不是红黑树,链表查询,查找不到就插入链表中,如果查找binCount >= TREEIFY_THRESHOLD - 1次转化为红黑树。
static final int TREEIFY_THRESHOLD = 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)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//链表转化为红黑树
//前提 (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY),hashtable长度大于64
static final int MIN_TREEIFY_CAPACITY = 64;
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
//红黑树还不会,其他的就没看;

总结

HashMap 是非线程安全的。基于HashMap实现的,键值需要明确定义hashcode和equals,如果不重写的话,存在两个对象,equals相等,却hashcode不同。就可能出现问题了。因为是根据先hashcode查找,再根据equals查找的。
底层是hashtable,即数组加链表,当冲突长度>8并且hashtable长度>64转化为将链表转化为红黑树。

二、Hashtable

This class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value.
这个类实现了一个哈希表,它将键映射到值。任何非空对象都可以用作键或值。
线程安全

 
//底层还是hash表
private transient Entry<?,?>[] table;
//多了是否包含值
public synchronized boolean contains(Object value){
if (e.value.equals(value))//底层是equals
}

总结

一些方法加了synchronized修饰,线程安全的,查询效率较低,去掉了HashTable的contains方法,但是加上了containsValue()和containsKey()方法。需要重写hashCode()和equals()。底层还是哈希表

TreeMap

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
一种基于红黑树的NavigableMap实现的。根据其键的自然顺序或在map创建时提供的比较器对map进行排序,具体取决于使用哪种构造函数。

 
//树根
private transient Entry<K,V> root;
//二叉树
static final class Entry<K,V> implements Map.Entry<K,V> {
K key;
V value;
Entry<K,V> left;
Entry<K,V> right;
Entry<K,V> parent;
boolean color = BLACK;
}
//一切获取比较,都是根据Comparable接口的方法来实现的,相同就覆盖,不同就插入
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
public K firstKey();//最小的键
public K lastKey();//最大的键
final Entry<K,V> getFirstEntry();//最小的键对
final Entry<K,V> getLastEntry() ;//最大的键对
final Entry<K,V> getLowerEntry(K key);//位于key前一维的键值对
final Entry<K,V> getHigherEntry(K key) ;//位于key后一维的键值对
//其他看不懂。

总结

适用于按自然顺序或自定义顺序遍历键(key)。两种方式排序:自然排序和比较器排序。

总结

HashMap和HashTable需要重写hashcode和equals方法,HashTable线程安全,而HashMap是非同步的,效率上比HashTable要高,HashMap允许空键值,而HashTable不允许。
Treemap可以自定义排序规则。

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值