HashMap源码分析记录
HashMap继承了AbstractMap,并实现了Map接口、Cloneable, Serializable接口,作为Map键值对稽核体系中最常用的一个实现类,允许空键和空值,不允许键重复,允许值重复,非线程安全。
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
}
* HashMap的数据结构:HashMap底层数据结构为可存储链表或树的Entry对象数组,存储键值对时,会对传入的键进行hash运算,得到一个hash值,以此得到该键值对(Entry对象,在HashMap中是用其子类Node(K,V)存储)存在对象数组的哪个索引位置,当传入的键值对的Key计算出的hash值与对象数组中某个索引位置的键值对的Key的hash值相同,即为hash冲突,发生hash冲突后,HashMap会将后面的键值对以链表的形式加入到原有元素的后面,当链表长度达到8并且对象数组容量达到64时,会将链表结构转换为树结构,以提高查找的性能。当链表长度小于等于6时,又会将树结构转为链表结构。
1、成员变量
a、序列化Id:private static final long serialVersionUID = 362498820763181265L;
private static final long serialVersionUID = 362498820763181265L;
b、默认初始容量DEFAULT_INITIAL_CAPACITY
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
默认的初始容量为[16]
c、最大容量MAXIMUM_CAPACITY
static final int MAXIMUM_CAPACITY = 1 << 30;
最大容量限制为2^30
d、默认的负载系数DEFAULT_LOAD_FACTOR
static final float DEFAULT_LOAD_FACTOR = 0.75f;
默认的负载系数为0.75,当Map中键值对个数大于当前容量的0.75时会进行扩容
e、当hash冲突时存储的键值对由链表转换为树结构的判断条件之一TREEIFY_THRESHOLD
static final int TREEIFY_THRESHOLD = 8;
f、由树结构转为链表结构的阀值UNTREEIFY_THRESHOLD
static final int UNTREEIFY_THRESHOLD = 6;
g、链表结构转换为树结构的判断条件之一MIN_TREEIFY_CAPACITY
static final int MIN_TREEIFY_CAPACITY = 64;
当数组容量大于64且数组中的链表节点大于8时会将链表结构转换为树结构,否则只会扩容
h、存储键值对的对象数组table
transient Node<K,V>[] table;
i、缓存键对象和值对象的Set集合entrySet
transient Set<Map.Entry<K,V>> entrySet;
j、Map中存储的键值对对象数size
transient int size;
k、修改因子modCount,每次修改(添加、删除、移动、扩容、重新hash等)都会自增,用于实现fast-fail机制
transient int modCount;
l、扩容阀值int threshold;是容量*负载系数的值,当容量达到大于该值时,会进行扩容并设置新的阀值
int threshold;
m、负载因子final float loadFactor;
final float loadFactor;
2、内部类
a、存储键值对的类Node<K,V>
//该类实现了Map接口的内部类Entry
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
//存储下一个链表或树节点的地址
Node<K,V> next;
//构造一个键值对的节点对象
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
//修改键值对的V值
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
b、获取Map的Key对象的类KeySet
final class KeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<K> iterator() { return new KeyIterator(); }
public final boolean contains(Object o) { return containsKey(o); }
public final boolean remove(Object key) {
return removeNode(hash(key), key, null, false, true) != null;
}
public final Spliterator<K> spliterator() {
return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super K> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
c、获取Key、Value值映射对象的类EntrySet
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
public final boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Node<K,V> candidate = getNode(hash(key), key);
return candidate != null && candidate.equals(e);
}
public final boolean remove(Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Object value = e.getValue();
return removeNode(hash(key), key, value, true, true) != null;
}
return false;
}
public final Spliterator<Map.Entry<K,V>> spliterator() {
return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
3、构造方法
a、构造一个指定容量及负载系数的HashMap:public HashMap(int initialCapacity, float loadFactor)
public HashMap(int initialCapacity, float loadFactor) {
//传入的参数为容量及负载因子
//判断参数的合法性
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
//将传入的负载因子赋值给成员变量里的loadFactor
this.loadFactor = loadFactor;
//计算扩容阀值
this.threshold = tableSizeFor(initialCapacity);
}
b、构造一个指定容量的HashMap实例public HashMap(int initialCapacity)
public HashMap(int initialCapacity) {
//直接调用上面的方法,并将负载因子设置为默认的0.75
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
c、构造一个HashMap实例public HashMap()
public HashMap() {
//使用默认负载因子
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
d、构造一个包含指定Map的HashMap实例public HashMap(Map<? extends K, ? extends V> m)
public HashMap(Map<? extends K, ? extends V> m) {
//使用默认负载因子
this.loadFactor = DEFAULT_LOAD_FACTOR;
//调用存放Map集合的方法将传入的集合添加到HashMap中
putMapEntries(m, false);
}
4、成员方法
a、计算hash散列的方法hash()
static final int hash(Object key) {
int h;
//根据传入的键运用位运算来获取冲突小的hash散列值并返回
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
b、扩容方法tableSizeFor
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
得到传入的参数的两倍并返回
c、将传入的Map放到HashMap中 putMapEntries(Map<? extends K, ? extends V> m, boolean evict)
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
//如果HashMap为空,则计算扩容阀值
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
//调用阀值计算方法并将返回值赋值给内置的扩容阀值
threshold = tableSizeFor(t);
}
//原HashMap不为空,传入的集合size大于扩容阀值,则进行扩容
else if (s > threshold)
resize();
//遍历传入的集合,并将键值对放入原HashMap中
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
d、返回映射中的键值对数public int size()
public int size() {
return size;
}
e、判断HashMap是否为空public boolean isEmpty()
public boolean isEmpty() {
return size == 0;
}
f、根据键获取值get(K key)
public V get(Object key) {
Node<K,V> e;
//获取值
//先获取Node数组的值,判断是否为空,为空返回null,不为空返回value
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//获取Node数组中元素的方法
final Node<K,V> getNode(int hash, Object key) {
//定义变量
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//判断条件:Node键值对数组不为空,数组的length大于0,根据n-1&hash与运算得到的数组索引的值不为空
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);
}
}
//都没有则返回null
return null;
}
g、判断HashMap是否包含传入的键对应的映射public boolean containsKey(Object key)
public boolean containsKey(Object key) {
//调用此方法并判断非空才返回ture
return getNode(hash(key), key) != null;
}
h、将键值对放入HashMap中public V put(K key, V value),如果key在HashMap中已存在,则会覆盖该键所对应的value值
public V put(K key, V value) {
//调用方法
return putVal(hash(key), key, value, false, true);
}
//将键值对放入HashMap的Node数组中的方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//判断Node数组是否为空,为空则进行初始化扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//根据与运算得到的索引位置为空,则新建一个Node对象,放入该位置
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;
//如果Node数组为树结构,则将该键值对放到树结构中
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//为链表结构,则循环
for (int binCount = 0; ; ++binCount) {
//Node节点的下一个节点为空,则将传入的键值对放入
if ((e = p.next) == null) {
//新增节点
p.next = newNode(hash, key, value, null);
//如果链表长度大于等于树结构转换阀值,即8,则将对是否转换为树结构进行判断
//如果Node数组的容量小于等于64,则不转换,否则将链表转换为树结构
//binCount为链表的索引,当binCount大于等于7时,即链表的元素个数达到了8个及以 上,会进行转换为树结构的判断
//在进行binCount判断时,新节点实际已经加入链表了,比如binCount为7,链表有8个 节点,执行到这里时实际上链表中已有9个节点了
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果链表中有相同的key,则进行跳出循环,替换value
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;
}
i、扩容方法final Node<K,V>[] resize(),返回Node键值对数组
final Node<K,V>[] resize() {
//将原数组定义为oldTab
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//新容量为原容量左移1位,即为原来的2倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//新的扩容阀值也为原扩容阀值的2倍(左移1位)
newThr = oldThr << 1; // double threshold
}
//如果原容量为0(即首次添加元素)
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
//将容量设置为默认容量16
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//将新的阀值赋值给原阀值
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
//新建一个包含新容量大小的键值对数组并赋值给原数组
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//原数组不为空
if (oldTab != null) {
//遍历数组的元素
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
//原数组的元素置为空
oldTab[j] = null;
if (e.next == null)
//如果元素位置没有链表,则直接将新数组的索引位置放置原数组的元素
//新数组的元素的index的计算方法为元素的hash属性与上新容量-1得到index
newTab[e.hash & (newCap - 1)] = e;
//如果该Node上是树结构,则会重新对结构进行判断,新容量大于64且元素个数大于等于8,则 还是采用树结构存储,否则转换为链表
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//否则存储的元素为链表,将链表的数据放到新数组中
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
//遍历链表
do {
//将e.next赋给next变量
next = e.next;
//通过与运算惊喜判定该元素是在链表的低位还是高位
if ((e.hash & oldCap) == 0) {
if (loTail == null)
//指定低位链表的头结点
loHead = e;
else
loTail.next = e;
//指定尾节点
loTail = e;
}
//高位
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
//while条件里相当于e = e.next,元素进行了迭代
} while ((e = next) != null);
//上面的循环遍历链表生成了两条新的链表,低位链表和高位链表
if (loTail != null) {
//低位链表的尾节点不为空,则将其next节点置空
loTail.next = null;
//将低位链表的头结点放入新数组的索引位置处
newTab[j] = loHead;
}
if (hiTail != null) {
//高位链表的尾节点不为空,则将其next节点置空
hiTail.next = null;
//将高位链表的头结点放入新数组的索引+原数组容量的位置处
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
//红黑树扩容
//参数:map:旧数组,tab:新数组,index:当前遍历到的数组元素的索引,bit:原数组的长度
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
//保存当前元素为b
TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
//定义高位低位节点
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
//遍历红黑树
for (TreeNode<K,V> e = b, next; e != null; e = next) {
next = (TreeNode<K,V>)e.next;
e.next = null;
//通过运算得到高位低位的链表
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
//得到的低位链表的元素个数
++lc;
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
//高位链表的元素个数
++hc;
}
}
//遍历完成之后,此时树的结构并没有发生改变
//判断低位的头节点
if (loHead != null) {
//如果低位链表的元素个数小于等于6
if (lc <= UNTREEIFY_THRESHOLD)
//则会将该链表退化为链表结构,并将头节点移到新数组的与旧数组相同的位置
tab[index] = loHead.untreeify(map);
else {
//不退化的情况,将低位链表的头节点放到新数组与原来数组的位置相同的位置
tab[index] = loHead;
//如果高位链表的头节点不为空,则要将低位链表重新树化
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
if (hiHead != null) {
//如果高位链表的元素个数小于等于6
if (hc <= UNTREEIFY_THRESHOLD)
//则会将该链表退化为链表结构,并将头节点移到新数组中索引为原索引+旧数组容量的位置
tab[index + bit] = hiHead.untreeify(map);
else {
//不退化的情况
tab[index + bit] = hiHead;
if (loHead != null)
//如果低位链表的头节点不为空,则要将高位链表重新树化
hiHead.treeify(tab);
}
}
}
j、hash冲突时链表与树结构转换的判断方法final void treeifyBin(Node<K,V>[] tab, int hash)
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//判断数组的容量是否大于等于64
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
//小于64,则进行扩容
resize();
//否则进行树化转换
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
//将链表转换为TreeNode类型的双向链表
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);
}
}
//树化的具体
final void treeify(Node<K,V>[] tab) {
TreeNode<K,V> root = null;
//遍历循环双向链表,将链表的第一个元素设为红黑树的root节点
for (TreeNode<K,V> x = this, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
x.left = x.right = null;
if (root == null) {
x.parent = null;
x.red = false;
root = x;
}
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
for (TreeNode<K,V> p = root;;) {
int dir, ph;
K pk = p.key;
//比较新插入节点与已插入节点的hash值
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
//hash值相等的情况
else if ((kc == null &&
//判断插入的元素的key值是否实现了Comparable接口,实现了则返回key 的class对象,否则返回null
(kc = comparableClassFor(k)) == null) ||
//比较新插入的元素的key与原有元素的key的大小
(dir = compareComparables(kc, k, pk)) == 0)
//调用原生默认的hashcode方法对元素进行比较,获得dir值
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
//dir值小于等于0,走左边,大于0,走右边,如果左子树或右子树为空
if ((p = (dir <= 0) ? p.left : p.right) == null) {
//设置新插入的节点的父节点
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
//调用方法调整红黑树
root = balanceInsertion(root, x);
break;
}
}
}
}
//将红黑树的根节点设为tab数组的元素,并且将root原来在双向链表中的位置设为头节点(转为红黑树的过程中双 向链表的prev和next属性未发生该变)
moveRootToFront(tab, root);
}
static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
int n;
if (root != null && tab != null && (n = tab.length) > 0) {
int index = (n - 1) & root.hash;
//获取根据root元素的hash值算出的index位置的元素
TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
//得到的元素如果不是root对象,进行调整
if (root != first) {
Node<K,V> rn;
//将数组的index位置设为root
tab[index] = root;
//root对象在双向链表中的前节点
TreeNode<K,V> rp = root.prev;
//root对象在双向链表中的后节点不为空
if ((rn = root.next) != null)
//将root对象的前节点设为后节点的前节点
((TreeNode<K,V>)rn).prev = rp;
if (rp != null)
//前节点不为空,前节点的后节点为root对象的后节点
rp.next = rn;
if (first != null)
//如果原来数组位置上的元素不为空,将该元素的前节点设为root
first.prev = root;
//root后节点设为原来的元素,前节点置空
root.next = first;
root.prev = null;
}
//红黑树的最后判断
assert checkInvariants(root);
}
}
k、将传入的键值对集合放到HashMap中public void putAll(Map<? extends K, ? extends V> m)
public void putAll(Map<? extends K, ? extends V> m) {
//调用方法将集合元素放到HashMap中
putMapEntries(m, true);
}
l、移除传入的键对应的键值对public V remove(Object key)
public V remove(Object key) {
Node<K,V> e;
//返回移除的元素的value
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
//从Node键值对数组中移除相对应的元素
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//只有一个节点,将该值返回
node = p;
//如果有多个节点
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
//树结构
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
//链表结构
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
m、移除HashMap中所有的元素clear()
public void clear() {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}
n、判断HashMap是否包含传入的value值得键值对public boolean containsValue(Object value)
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}
o、返回一个KeySet视图public Set<K> keySet(),用于通过键取值等
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
p、移除HashMap中指定键值对元素public boolean remove(Object key, Object value)
public boolean remove(Object key, Object value) {
return removeNode(hash(key), key, value, true, true) != null;
}
q、替换指定key的value值public boolean replace(K key, V oldValue, V newValue)
public boolean replace(K key, V oldValue, V newValue) {
Node<K,V> e; V v;
if ((e = getNode(hash(key), key)) != null &&
((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
e.value = newValue;
afterNodeAccess(e);
return true;
}
return false;
}
//替换的重载方法
public V replace(K key, V value) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) != null) {
V oldValue = e.value;
e.value = value;
afterNodeAccess(e);
return oldValue;
}
return null;
}
4、补充
a、红黑树特点
- 每个节点可以是红的或者黑的
- 根节点是黑的
- 每个叶子节点是黑的
- 如果一个节点是红的,则它的两个子节点都是黑的
- 对于每个节点,从该节点到其任何叶子节点的所有路径上包含相同数目的黑色节点
b、新增一个节点,都假设为红色
c、变色、旋转的情况
新节点设置为红色
父节点是黑色,不用调整
父节点是红色:
- 叔叔节点为空,旋转、变色(左旋还是右旋看新节点插在父节点的左边还是右边)
- 叔叔是红色,父节点+叔叔节点变黑色,祖父节点变红色
- 叔叔是黑色,旋转、变色
HashMap中红黑树平衡方法
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root, TreeNode<K,V> x) { x.red = true; //root:根节点,x:插入的新节点,xp:插入节点的父节点,xpp:插入节点的祖父节点,xppl:插入节点的祖父节点的左子节点,xppr:插入节点的祖父节点的右子节点 //对树进行循环 for (TreeNode<K,V> xp, xpp, xppl, xppr;;) { //如果插入节点的父节点为空,则该节点为树的第一个节点,直接返回 if ((xp = x.parent) == null) { x.red = false; return x; } //如果插入节点的父节点为黑色,或者祖父节点为空,则父节点为根节点 else if (!xp.red || (xpp = xp.parent) == null) return root; //如果父节点为祖父节点的左子节点 if (xp == (xppl = xpp.left)) { //祖父节点有右子节点,即插入节点有叔叔节点,并且为红色 if ((xppr = xpp.right) != null && xppr.red) { //叔叔节点变黑,父节点变黑,祖父节点变红 xppr.red = false; xp.red = false; xpp.red = true; //再将祖父节点赋值为x,递归进行调整 x = xpp; } //如果不存在叔叔节点 else { //如果新节点为父节点的右子节点,则进行左旋 if (x == xp.right) { root = rotateLeft(root, x = xp); //新节点的父节点若不为空,则获取祖父节点 xpp = (xp = x.parent) == null ? null : xp.parent; } //父节点不为空 if (xp != null) { //父节点变黑 xp.red = false; //祖父节点不为空 if (xpp != null) { //祖父节点变红 xpp.red = true; //右旋 root = rotateRight(root, xpp); } } } } //如果父节点为祖父节点的右子节点 else { //如果存在叔叔节点且叔叔节点为红色 if (xppl != null && xppl.red) { //叔叔节点变黑,父节点变黑,祖父节点变红 xppl.red = false; xp.red = false; xpp.red = true; //递归查找 x = xpp; } //如果不存在叔叔节点 else { //新节点为父节点左子节点 if (x == xp.left) { //右旋 root = rotateRight(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null) { xp.red = false; if (xpp != null) { xpp.red = true; //左旋 root = rotateLeft(root, xpp); } }j } } } } //左旋方法 static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root, TreeNode<K,V> p) { TreeNode<K,V> r, pp, rl; if (p != null && (r = p.right) != null) { if ((rl = p.right = r.left) != null) rl.parent = p; if ((pp = r.parent = p.parent) == null) (root = r).red = false; else if (pp.left == p) pp.left = r; else pp.right = r; r.left = p; p.parent = r; } return root; } ~~~
版权声明:本文为qq_44583593原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。