简介
key-value 的键值对,key 不允许重复,value 可以
- 严格来说 Map 并不是一个集合,而是两个集合之间 的映射关系。(数组–链表)
- 这两个集合每一条数据通过映射关系,我们可以看成是一条数据。即 Entry(key,value)。Map 可以看成是由多个 Entry 组成。
- 因为 Map 集合即没有实现于 Collection 接口,也没有实现 Iterable 接口,所以不能对 Map 集合进行 for-each 遍历。
HashMap
- HashMap 的实现不是同步的,这意味着它不是线程安全的。它的key、value都可以为null。此外,HashMap中的映射不是有序的。
- HashMap 的实例有两个参数影响其性能:“初始容量” 和 “加载因子”。容量 是哈希表中桶的数量,初始容量 只是哈希表在创建时的容量。加载因子 是哈希表在其容量自动增加之前可以达到多满的一种尺度。当哈希表中的条目数超出了加载因子与当前容量的乘积时,则要对该哈希表进行 rehash 操作(即重建内部数据结构),从而哈希表将具有大约两倍的桶数。
新建HashMap,构造器源码:
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;
threshold = initialCapacity;
init();
}
public HashMap(int initialCapacity) {
// 带有一个参数的构造器,也是调用自己的带有两个参数的构造器
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
// 无参构造器,调用的是自己的带有两个参数的构造器。
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
public HashMap(Map<? extends K, ? extends V> m) {
this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
inflateTable(threshold);
putAllForCreate(m);
}
默认加载因子是:0.75,默认创建hashMap大小: 16
/**
* 默认大小, 左移位4.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 加载因子0.75
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
面试常问的问题:hashmap怎么存储的?怎么扩容,扩容多少?怎么取值得?
存储规则:
下面代码只是源码的一部分,只是方便查看,加深理解,不能直接运行使用
map.put(key, value);
调用如下源码
// table 实际上是 Entry数组
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
public V put(K key, V value) {
// 判断存储的Entry数组是否为空的(Map底层存储实际上是Entry数组)
if (table == EMPTY_TABLE) {
//初始化Entry数组
inflateTable(threshold);
}
// 如果key==null, 特殊存储
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
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);
return null;
}
/**
* 初始化Entry数组(table)
*/
private void inflateTable(int toSize) {
// Find a power of 2 >= toSize
int capacity = roundUpToPowerOf2(toSize);
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;
}
/**
*存储空对象的方法
*/
private V putForNullKey(V value) {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}
// hash值计算方法
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
mber of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
通过上面源码可以看出,在往map中存数据的流程为:
1. 查看table是否为空(底层Entry数组是否为空)if (table == EMPTY_TABLE)
2. 如果table为空,扩容,为原来的两倍(通过左移一位来实现的)Integer.highestOneBit((number - 1) << 1)
3. table不为空,下一步
4. 判断key==null
5. 满足:把key==null的value存储到key为null的map中 putForNullKey(value);
6. 否则下一步
7. 计算key的hash值 int hash = hash(key)
; (计算hash值得算法贴出来,这里不再解释,自己看)
8. 通过上面计算的hash值,寻找在table中的存储位置 int i = indexFor(hash, table.length)
;
9. 执行存值逻辑。
public void putAll(Map<? extends K, ? extends V> m) {
int numKeysToBeAdded = m.size();
if (numKeysToBeAdded == 0)
return;
if (table == EMPTY_TABLE) {
inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold));
}
/*
* 扩容逻辑
*/
if (numKeysToBeAdded > threshold) {
int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
if (targetCapacity > MAXIMUM_CAPACITY)
targetCapacity = MAXIMUM_CAPACITY;
int newCapacity = table.length;
while (newCapacity < targetCapacity)
//移位扩容
newCapacity <<= 1;
if (newCapacity > table.length)
//这里也是一个知识点:扩容导致的问题 (@2)
resize(newCapacity);
}
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
put(e.getKey(), e.getValue());
}
第二种存储方法,大体同第一种, 代码写的更加清晰。不在赘述
注意:
@1、关于存储的问题:这里在说一下存储的流程。因为面试多次问道,所以这里在啰嗦几句
问题:首先是根据key的hash值去寻找存储的位置,一般不同key的hash值不同,但是也有很小的可能性是相同的
所以,导致一个问题。假如key=A,hash值为100,存储到table的索引也假设为100. 又存储一个key=B的存进来,hash值计算出来也是100.那么存储到table的索引也是100. 但是table的100位置已经存上key=A的数据了,这里就牵扯到另一个问题。hash值相同的话,value怎么存储?
答案:通过源码可以看出,table是一个Entry对象数组。数组里面存储的就是key值,value值,hash值,next下个节点引用, 如果有上面出现的情况, 那么会在创建一个链表节点(新建一个Entry对象),存储上新值。放在链表第一个位置(注意后添加的value是存在链表第一个位置,这里不是后面追加)源码下面贴出来,想看的可以看看:
void addEntry(int hash, K key, V value, int bucketIndex) {
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 createEntry(int hash, K key, V value, int bucketIndex) {
//取出该位置以前的值
Entry<K,V> e = table[bucketIndex];
// 新建一个节点
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
Entry(int h, K k, V v, Entry<K,V> n) {
value = v; //value值
next = n; //把旧的节点放到下个节点
key = k; //key值
hash = h; // hash值
}
下面我自己按照自己的理解画了一个草图,可以了解下(不太清晰),下面网上的图也也挺好的
@2、resize(newCapacity);
扩容导致的需要在建一个比较大的table(Entry对象数组),所以会出现复制old_table里的数据到new_table的问题。其中牵扯到再次计算hash值。去存到new_table里,1->影响性能,2->如果用到多线程中,还会导致并发问题(因为HashMap不是线程安全的,如果用到多线程里,也只能说写程序的人技术不行。哈哈)。所以能确定长度,就在新建map时候,吧容量写上。
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);
}
/**
* 复制老数据到新Entry对象数组中
*/
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next;
if (rehash) {
// 重新计算hash值
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
获取值规则
取值源码
public V get(Object key) {
if (key == null)
// key为空的情况
return getForNullKey();
//不为空的情况
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
private V getForNullKey() {
if (size == 0) {
return null;
}
//循环找出key==null的情况
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
//算出hash值
int hash = (key == null) ? 0 : hash(key);
// 又一次验证了上面说的特殊情况
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
源码很简单不在解释, 这里在说一下上面存储里遇见的特殊情况(hash值相同)。这里取值中也出现了我们说的情况
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
算出索引后,循环的目的就是为了验证是否存在hash值相同,多个value值得情况。(怎么取出我们想要的,通过key的equals方法来得到我们需要的value。因为hash值相同,key一定不同,否则hash相同,key也相同,那就是覆盖之前的值,不会出现链表的情况。)