请你给我Java 的HashMap数据结构的源码
时间: 2023-03-12 17:37:51 浏览: 109
JDK5HashMap源码
HashMap 数据结构的源码如下:public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable { private static final long serialVersionUID = 362498820763181265L; // 默认容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 // HashMap的最大容量
static final int MAXIMUM_CAPACITY = 1 << 30; // 默认负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f; // 当HashMap中的实际元素超过了其容量*负载因子时,HashMap的容量就会动态增加
transient int size; // HashMap中实际存放元素的数组
transient Node<K,V>[] table; // HashMap的负载因子
final float loadFactor; // HashMap扩容时,阈值,当HashMap中实际元素数量超过了该阈值时,HashMap会自动扩容
int threshold; // HashMap结构被修改的次数
transient int modCount; // 构造函数
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);
} // 返回能够容纳capacity个元素的HashMap的容量
static final int tableSizeFor(int capacity) {
int n = capacity - 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;
}
}
阅读全文