简介
hashmap 存储是无序的
hashmap 的底层原理:
实现:数组 + 链表 +(红黑树)
Note : hash key values Node<>
默认创建16大小的数组 Node<K,V>[] (到length 的0.75 时进行扩容 2的幂次方16->32)
数组的每个存储单元为 节点Note<K,V>
在数组中通过 计算hash 值来确定存储位置 hash算法 (h = key.hashCode()) ^ (h >>> 16) key的hashcode
当hash值相同时会比较 equal方法
会比较equal 方法 和hashcode
在数组长度 64 和链表长度 8 时 将链表转化为 红黑树。
节点类
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);
}
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;
}
}
//TreeNode 节点
服务
//这个三个方法都是为了继承HashMap的LinkedHashMap类服务的。
//LinkedHashMap 是 HashMap 的一个子类,它保留插入的顺序,如果需要输出的顺序和输入时的相同,那么就选用 LinkedHashMap。
void afterNodeAccess(Node<K,V> p) {
}
void afterNodeInsertion(boolean evict) {
}
void afterNodeRemoval(Node<K,V> p) {
}
构造方法
// initialCapacity 初始容量
// the load factor 复合系数
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);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
// initialCapacity 初始容量
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
//
public HashMap() {
this