结合问题:HashMap内部的结构是怎么样的?红黑树有什么特性?红黑树的时间复杂度是多少?理想中的HashMap的时间复杂度是多少?
相关文章:[数据结构:HashMap](()
相关视频:[https://www.bilibili.com/video/av75970633](()
1、HashMap内部的结构是怎么样的?体现在哪里?
==========================
数组的体现:
单项链表的体现:
红黑树的体现:
2、为什么HashMap的初始容量必须是2的倍数?
=========================
/**
- The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
答案是为了方便实现"与"运算(&)
及时你传入的不是2的倍数,代码里也会自动帮你调整。
/**
- Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 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;
}
3、Node里面有个hash的整型参数,为什么要保存?
===========================
键值对的意义自不用说,next是链表的标志,那么 int hash有什么用为什么要单独声明一个参数呢?
这是因为这个值的获取来之不易,经历了四个步骤才获取到,所以要保存一下:
-
保证HashMap的容量capacity是2的倍数,
-
获取存入值的HashCode
-
将HashCode的高16位和低16进行与运算,得到result
-
将上一步的result和(capacity-1)进行与运算。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
3、什么情况下转为红黑树,代码体现?
==================
代码体现:
static final int TREEIFY_THRESHOLD = 8;
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
…
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
…
}
4、红黑树有什么特性?红黑树的时间复杂度是多少?理想中的HashMap的时间复杂度是多少?
=============================================
4.1、红黑树有什么特性?
4.2、红黑树的时间复杂度是多少?
4.3、理想中的HashMap的时间复杂度是多少?
O(logN)
其他面试题:
1. HashMap的底层原理是什么?线程安全么? 百度 美团
2. HashMap中put是如何实现的? 滴滴
4. 什么是哈希碰撞?怎么解决? 滴滴 美团
5. HashMap和HashTable的区别 小米
6. HashMap中什么时候需要进行扩容,扩容resize()是如何实现的? 滴滴
7. hashmap concurrenthashmap原理 美团
8. arraylist和hashmap的区别,为什么取数快?字节跳动
5、HashMap的底层原理是什么?线程安全么?
========================
[https://blog.youkuaiyun.com/songzi1228/article/details/99974540](()
HashMap底层是数组+链表,链表数据超过8个转为红黑树。不是线程安全的。作为对比,HashTable是线程安全的,因为HashTable对外提供的方法都加上了synchronized。
6、谈一下hashMap中什么时候需要进行扩容,扩容resize()又是如何实现的?
==========================================
/**
- The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
-
The next size value at which to resize (capacity * load factor).
-
@serial
*/
int threshold;
// threshold 赋值
final Node<K,V>[] resize() {
…
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
threshold = newThr;
…
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,