HashMap 添加元素
public V put(K key, V value) {
if (table == EMPTY_TABLE) {//如果当前table即(Entry[])为空,则初始化table
inflateTable(threshold);
}
if (key == null)//支持key为null
return putForNullKey(value);
int hash = hash(key);//获取key的hash值
int i = indexFor(hash, table.length);//获取数组下标i
for (Entry e = table[i]; e != null; e = e.next) {//遍历下标为i的链表,如果找到key,则赋值并返回旧值
Object k;
//这里先比较hash值,因为如果hash不相等则key值一定不相等,后面的equals方法在业务中可能会被重写,效率低。
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;//修改次数加1
addEntry(hash, key, value, i);//添加entry对象
return null;
}
private void inflateTable(int toSize) {
// 返回一个 >= toSize 的 2的幂次方,为什么要返回2的幂次方,下面获取table下标时再说
int capacity = roundUpToPowerOf2(toSize);
//阀值等于 数组容量x加载因子(0.75)
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);
}
private static int roundUpToPowerOf2(int number) {
// assert number >= 0 : "number must be non-negative";
return number >= MAXIMUM_CAPACITY
? MAXIMUM_CAPACITY
: (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
}
//(number - 1) << 1 得到的值大于number 且小于 number的2次方
//Integer.highestoneBit()方法返回小于等于参数的最大2的幂
public static int highestOneBit(int i) {
// HD, Figure 3-1
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
return i - (i >>> 1);
}
//假设初始值为 1*** ****
// >>1 01** ****
// 或运算 11** ****
// >>2 0011 ****
// 或运算 1111 ****
// >>4 0000 1111
// 或运算 1111 1111
//由此可以看出,该方法通过 右移和或运算将低位全部变成1
//由于int类型有32位,所以为了保证所有的情况,需要依次移动 1,2,3,8,16
//该方法的总体思路为,初始值为1*** ****,若想得到小于等于参数的最大2的幂,只需将低位全部改为0,即返回1000 0000
//第一步,通过一系列右移,先将所有低位变为1 ,得到 1111 1111
//第二步,右移一位,得到 0111 1111
//第三步,1111 1111 - 0111 1111 得到 1000 0000.
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
//这段代码被叫做扰动函数,通过将哈希值高位右移,然后进行异或运算来加大低位的随机性。
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
//传入 hash方法返回的值与(数组容量-1)进行与操作得到一个下标
//由于此前已经保证 length为2的幂,假如length为16,则length-1等于 0000 1111
// 注意 0000 1111 的高位全是0 ,低位全是1,所以不管h值有多大,与操作之后只与后4位有关,且范围为0-15,
//保证了得到的下标在数组长度范围之内
static int indexFor(int h, int length) {
return h & (length-1);
}
void addEntry(int hash, K key, V value, int bucketIndex) {
//如果size >= 阀值,则按当前长度的两倍扩容
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
//创建新的数组,并转移数据
Entry[] newTable = new Entry[newCapacity];
transfer(newTable, initHashSeedAsNeeded(newCapacity));
table = newTable;
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
//将所有元素转移到新数组
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry e : table) {//遍历数组,数组存的是链表的头节点
while(null != e) {//遍历链表,头节点为e
Entry next = e.next;//获取 next 节点
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);//重新获取e的下标
//以下两个步骤为头插法,首先将e指向新数组i位置的头节点即newTable[i]
//然后将newTable[i]的值设为e,此时e成为了新的头节点
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
void createEntry(int hash, K key, V value, int bucketIndex) {
//头插法添加数据,和上面方法一个原理
Entry e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
HashMap 遍历
//hashmap 可以通过 hashmap.entrySet().iterator() 获取迭代器,并遍历
//通过下面代码可以看出,最终返回的迭代器为HashIterator
public Set> entrySet() {
return entrySet0();
}
private Set> entrySet0() {
Set> es = entrySet;
return es != null ? es : (entrySet = new EntrySet());
}
private final class EntrySet extends AbstractSet> {
public Iterator> iterator() {
return newEntryIterator();
}
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry) o;
Entry candidate = getEntry(e.getKey());
return candidate != null && candidate.equals(e);
}
public boolean remove(Object o) {
return removeMapping(o) != null;
}
public int size() {
return size;
}
public void clear() {
HashMap.this.clear();
}
}
Iterator> newEntryIterator() {
return new EntryIterator();
}
private final class EntryIterator extends HashIterator> {
public Map.Entry next() {
return nextEntry();
}
}
private abstract class HashIterator implements Iterator {
Entry next; // next entry to return
int expectedModCount; // For fast-fail
int index; // current slot
Entry current; // current entry
HashIterator() {
//初始化时会将modCount 赋值给expectedModCount
expectedModCount = modCount;
if (size > 0) { // advance to first entry
Entry[] t = table;
//遍历数组,找到第一个链表,赋值给next
while (index < t.length && (next = t[index++]) == null)
;
}
}
public final boolean hasNext() {
return next != null;
}
final Entry nextEntry() {
//此处如果modCount 和 expectedModCount 值不相等会抛出异常
//所以遍历HashMap 并删除时,需要用这个迭代器自己的 remove 方法
//因为这个方法会在移除操作后修改expectedModCount
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Entry e = next;
if (e == null)
throw new NoSuchElementException();
//如果这个链表的next节点为null,说明这个链表到头了,然后遍历数组,寻找下一个链表,并赋值给next
if ((next = e.next) == null) {
Entry[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
current = e;
return e;
}
public void remove() {
if (current == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Object k = current.key;
current = null;
HashMap.this.removeEntryForKey(k);
expectedModCount = modCount;
}
}