public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>{
//默认初始化容量(必须是的2幂) - 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认的负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//空内容的数组
static final Entry<?,?>[] EMPTY_TABLE = {};
//hash数组/hash表
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;//{}
//元素个数
transient int size;//0
//阈值
int threshold;//16
//负载因子
final float loadFactor;//0.75f
//外部操作数
transient int modCount;//0
//hash种子数
transient int hashSeed = 0;
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
//initialCapacity - 16
//loadFactor - 0.75
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))//NaN - Not a Number
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
threshold = initialCapacity;
init();
}
//子类的初始化挂钩 -- 让LinkedHashMap重写
void init() {
}
}
HashMap<Student, String> map = new HashMap<>();
map.put(null, "赏花");//null
map.put(null, "抚琴");//赏花
map.put(new Student("唐宇", '男', 23, "2402", "001"), "踢足球");//null
map.put(new Student("基蒲", '男', 21, "2402", "002"), "看电影");//null
map.put(new Student("侯小康", '男', 22, "2402", "003"), "看抖音");//null
map.put(new Student("侯小康", '男', 22, "2402", "003"), "写代码");//看抖音
JDK1.7版的HashMap数据结构是什么?
一维数组+单向链表
HashMap的默认容量是多少?
16
HashMap阈值的作用是什么?
元素个数达到阈值,就扩容
HashMap的默认负载因子是多少?其作用是什么?
0.75
作用:数组长度*负载因子=阈值,负载因子决定扩容比例
HashMap的默认负载因子为什么是0.75?
0.75取得了空间和时间的平衡
负载因子过大(1),会导致数组装满后才扩容,利用了空间,浪费时间
负载因子过小(0.1),会导致数组装了一点点数据就扩容,利用了时间,浪费空间
HashMap的容量为什么必须是2的幂?
???
HashMap最大容量为什么多少?
1<<30
HashMap最大容量为什么是1<<30?
最大容量是int类型,1<<30为int类型取值范围里最大的2的幂的数字