HashMap interview will be asked six points, you know a few?

A, HashMap implementation principle?

This question can be asked the following composition chain gun

  • Have you seen the HashMap source Well, to understand the principle thing?

  • Why use an array + list?

  • hash conflict you know what the solution?

  • I use LinkedList instead of an array structure can it?

  • Since it is possible, why not HashMap LinkedList, and the choice of an array?

1. Have you seen the HashMap source Well, to understand the principle thing?

To address this issue, ah, of course, you must be seen HashMap source. As for the principle, the following picture is very clear:

v2-028e8e4d686a9c38d20cec86faeea880_b.jpg


Entry array to store HashMap using key-value pairs, each pair consisting of a key Entry Entity, Entry class is actually a one-way linked list structure having Next pointer, the entity may be connected to the next Entry.

When only the JDK1.8, chain length greater than 8, the list will be transferred into a red-black tree!

2. Why use an array + list?

An array is used to determine the bucket position, the key elements of the hash value obtained modulo the length of the array.

Hash linked list is used to resolve conflicts when the same situation occurs hash value, to a corresponding position on the array to form a linked list. ps: Here's hash value does not mean hashcode, but the level of sixteen different hashcode or off. As for why he does it, read on.

3.hash conflict you know what the solution?

There are four known comparison (1) Open-addressable (2) Method link address (3) re-hashing (4) common overflow area method

ps: we are interested in expanding their own to search what you understand, this is not to expand!

4. I use LinkedList instead of an array structure can it?

Here I explain a little, this question means that the source code is this

Entry[] table = new Entry[capacity];

ps: Entry is a list node.

I said this with the following

List<Entry> table = new LinkedList<Entry>();

Is it feasible?

The answer is obvious, it must be possible.

5. Since it is possible, why not HashMap LinkedList, and the choice of an array?

Because the array with the highest efficiency!

In the HashMap, position location bucket hash value using the key elements of the array obtained modulo length. At this point, we have been the position of the barrel. Obviously array of search efficiency is greater than LinkedList.

That ArrayList, but also the underlying array, also was quick look, why do not ArrayList?

(Smoke brother wrote here, can not help but feel that they really have the idea that he asked himself dead, but fortunately I had an idea to come up with the answer)

Because the use of the basic structure of the array, can define its own expansion mechanism, the expansion array in the HashMap exactly powers of 2, the modulo operation do high efficiency.

The expansion mechanism ArrayList expansion of 1.5 times, 1.5 times why that ArrayList expansion which is not in this article explains.


Two, HashMap expansion under what conditions?

This question can be asked the following composition chain gun

  • HashMap expansion under what conditions?

  • Why is the expansion of the n-th power of 2?

  • Why why the first exclusive high 16 or low 16 then modulo operation?

1.HashMap expansion under what conditions?

If the bucket is full (more than load factor * current capacity), it must resize.

load factor 0.75, in order to maximize avoid hash collision

current capacity as the current size of the array.

2. Why is the expansion of power of 2?

HashMap For efficient access, to try to lower the collision, is to try to assign a uniform data, substantially the same as the length of each chain, this implementation the data is stored in the linked list to an algorithm which; actual algorithm is modulo, hash% length.

However, we all know that such operations are not as fast shift operation.

Therefore, the source code is optimized hash & (length-1).

That hash% length == hash & (length-1)

That is why the n-th power of it?

Since the n-th power of 2 1 is actually behind the n-th power of n 0,2-1, n-1 is actually.

For example, when a length of 8, & 3 (8-1) = 3 & 2 (8-1) = 2, different positions, do not collide.

5 and a length of time, & 3 (5-1) = 0 2 (5-1) = 0, 0 in all, a collision occurs.

Therefore, to ensure that the volume is 2 ^ n, is to ensure that in doing (length-1) when each can & 1, that is, and with the 1111 ...... 1111111 operation.

3. Why why the first exclusive high 16 or low 16 then modulo operation?

I would like to look at the sun, jdk1.8 inside the hash method. 1.7 is more complex, I do not read.

v2-33c73d4d3586c9538cf5f508317327fa_b.jpg


hashmap we do so, just to reduce the chance of hash conflict.

Analogy, when our time length is 16, the hash code (character string "abcabcabcabcabc" key corresponding to the hash code) to (16-1) operation, the hashCode for a plurality of key generation, as long as the hash 4 to 0, no matter no matter how high the code change after final results are zero.

As shown below

v2-5a95f21bd53cbf0eeb9f45f2bde1a413_b.jpg

After adding the upper 16 bits or the lower 16 bits of the exclusive "perturbation function", the following results

v2-5887a5beb80bb37539b48a73b36c495c_b.jpg


You can see: a disturbance function optimization: 1954974080% 16 = 1954974080 & (16--1) = 0 after the disturbance function optimization: 1955003654% 16 = 1955003654 & (16--1) = 6 Clearly, reducing the chance of collision.


Third, talk about the hashmap get / put the process?

This question can be asked the following composition chain gun

  • You know the process hashmap put in elements of what it is?

  • Get to know the process hashmap element of what it is?

  • Which hash algorithm you know?

  • Talk about the realization of the String hashcode? (I asked this question many manufacturers)

1. know the process hashmap element is put in what it?

of the key hashCode () do the hash calculation, calculation index;

If you do not crash directly into the bucket inside;

If the collision, the presence of the buckets in the form of a linked list;

If collisions result in long chain (greater than or equal TREEIFY_THRESHOLD), put the list is converted into red-black trees (changes in JDK1.8);

If the node already exists on replacing old value (ensure the uniqueness of the key)

If the bucket is full (more than load factor * current capacity), it must resize.

2. Know the process hashmap get what elements of it?

of the key hashCode () do the hash calculation, calculation index;

If a direct hit in the bucket in the first node, the direct return;

如果有冲突,则通过key.equals(k)去查找对应的Entry;

  • 若为树,则在树中通过key.equals(k)查找,O(logn);

  • 若为链表,则在链表中通过key.equals(k)查找,O(n)。

3.你还知道哪些hash算法?

先说一下hash算法干嘛的,Hash函数是指把一个大范围映射到一个小范围。把大范围映射到一个小范围的目的往往是为了节省空间,使得数据容易保存。

比较出名的有MurmurHash、MD4、MD5等等

4.说说String中hashcode的实现?(此题频率很高)

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;
        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

String类中的hashCode计算方法还是比较简单的,就是以31为权,每一位为字符的ASCII值进行运算,用自然溢出来等效取模。

哈希计算公式可以计为s[0]31^(n-1) + s[1]31^(n-2) + … + s[n-1]

那为什么以31为质数呢?

主要是因为31是一个奇质数,所以31*i=32*i-i=(i<<5)-i,这种位移与减法结合的计算相比一般的运算快很多。


四、为什么hashmap的在链表元素数量超过8时改为红黑树?

此题可以组成如下连环炮来问

  • 知道jdk1.8中hashmap改了啥么?

  • 为什么在解决hash冲突的时候,不直接用红黑树?而选择先用链表,再转红黑树?

  • 我不用红黑树,用二叉查找树可以么?

  • 那为什么阀值是8呢?

  • 当链表转为红黑树后,什么时候退化为链表?

1.知道jdk1.8中hashmap改了啥么?

  • 数组+链表的结构改为数组+链表+红黑树

  • 优化了高位运算的hash算法:h^(h>>>16)

  • 扩容后,元素要么是在原位置,要么是在原位置再移动2次幂的位置,且链表顺序不变。

最后一条是重点,因为最后一条的变动,hashmap在1.8中,不会在出现死循环问题。

2.为什么在解决hash冲突的时候,不直接用红黑树?而选择先用链表,再转红黑树?

因为红黑树需要进行左旋,右旋,变色这些操作来保持平衡,而单链表不需要。

当元素小于8个当时候,此时做查询操作,链表结构已经能保证查询性能。当元素大于8个的时候,此时需要红黑树来加快查询速度,但是新增节点的效率变慢了。

因此,如果一开始就用红黑树结构,元素太少,新增效率又比较慢,无疑这是浪费性能的。

3.我不用红黑树,用二叉查找树可以么?

可以。但是二叉查找树在特殊情况下会变成一条线性结构(这就跟原来使用链表结构一样了,造成很深的问题),遍历查找会非常慢。

4.那为什么阀值是8呢?

不知道,等jdk作者来回答。

这道题,网上能找到的答案都是扯淡。

我随便贴一个牛客网的答案,如下图所示

v2-99ce85526b4520a618f3183d9fbb38f0_b.jpg


看出bug没?交点是6.64?交点分明是4,好么。

log4=2,4/2=2。

jdk作者选择8,一定经过了严格的运算,觉得在长度为8的时候,与其保证链表结构的查找开销,不如转换为红黑树,改为维持其平衡开销。

5.当链表转为红黑树后,什么时候退化为链表?

为6的时候退转为链表。中间有个差值7可以防止链表和树之间频繁的转换。假设一下,如果设计成链表个数超过8则链表转换成树结构,链表个数小于8则树结构转换成链表,如果一个HashMap不停的插入、删除元素,链表个数在8左右徘徊,就会频繁的发生树转链表、链表转树,效率会很低。


五、HashMap的并发问题?

此题可以组成如下连环炮来问

  • HashMap在并发编程环境下有什么问题啊?

  • 在jdk1.8中还有这些问题么?

  • 你一般怎么解决这些问题的?

HashMap在并发编程环境下有什么问题啊?

  • (1)多线程扩容,引起的死循环问题

  • (2)多线程put的时候可能导致元素丢失

  • (3)put非null元素后get出来的却是null

在jdk1.8中还有这些问题么?

在jdk1.8中,死循环问题已经解决。其他两个问题还是存在。

你一般怎么解决这些问题的?

比如ConcurrentHashmap,Hashtable等线程安全等集合类。


六、你一般用什么作为HashMap的key?

此题可以组成如下连环炮来问

  • 健可以为Null值么?

  • 你一般用什么作为HashMap的key?

  • 我用可变类当HashMap的key有什么问题?

  • 如果让你实现一个自定义的class作为HashMap的key该如何实现?

1.健可以为Null值么?

必须可以,key为null的时候,hash算法最后的值以0来计算,也就是放在数组的第一个位置。

v2-7fd00d98896d91a366cdb5b4e4415a02_b.jpg


2.你一般用什么作为HashMap的key?

一般用Integer、String这种不可变类当HashMap当key,而且String最为常用。

  • (1)因为字符串是不可变的,所以在它创建的时候hashcode就被缓存了,不需要重新计算。这就使得字符串很适合作为Map中的键,字符串的处理速度要快过其它的键对象。这就是HashMap中的键往往都使用字符串。

  • (2)因为获取对象的时候要用到equals()和hashCode()方法,那么键对象正确的重写这两个方法是非常重要的,这些类已经很规范的覆写了hashCode()以及equals()方法。


3.我用可变类当HashMap的key有什么问题?

hashcode可能发生改变,导致put进去的值,无法get出,如下所示

HashMap<List<String>, Object> changeMap = new HashMap<>();
List<String> list = new ArrayList<>();
list.add("hello");
Object objectValue = new Object();
changeMap.put(list, objectValue);
System.out.println(changeMap.get(list));
list.add("hello world");//hashcode发生了改变
System.out.println(changeMap.get(list));

输出值如下

java.lang.Object@74a14482
null


4.如果让你实现一个自定义的class作为HashMap的key该如何实现?

此题考察两个知识点

  • 重写hashcode和equals方法注意什么?

  • 如何设计一个不变类

针对问题一,记住下面四个原则即可

(1)两个对象相等,hashcode一定相等

(2)两个对象不等,hashcode不一定不等

(3)hashcode相等,两个对象不一定相等

(4)hashcode不等,两个对象一定不等

针对问题二,记住如何写一个不可变类

(1)类添加final修饰符,保证类不被继承。

如果类可以被继承会破坏类的不可变性机制,只要继承类覆盖父类的方法并且继承类可以改变成员变量值,那么一旦子类以父类的形式出现时,不能保证当前类是否可变。

(2)保证所有成员变量必须私有,并且加上final修饰

通过这种方式保证成员变量不可改变。但只做到这一步还不够,因为如果是对象成员变量有可能再外部改变其值。所以第4点弥补这个不足。

(3)不提供改变成员变量的方法,包括setter

避免通过其他接口改变成员变量的值,破坏不可变特性。

(4)通过构造器初始化所有成员,进行深拷贝(deep copy)

如果构造器传入的对象直接赋值给成员变量,还是可以通过对传入对象的修改进而导致改变内部变量的值。例如:

public final class ImmutableDemo {  
    private final int[] myArray;  
    public ImmutableDemo(int[] array) {  
        this.myArray = array; // wrong  
    }  
}

这种方式不能保证不可变性,myArray和array指向同一块内存地址,用户可以在ImmutableDemo之外通过修改array对象的值来改变myArray内部的值。

为了保证内部的值不被修改,可以采用深度copy来创建一个新内存保存传入的值。正确做法:

public final class MyImmutableDemo {  
    private final int[] myArray;  
    public MyImmutableDemo(int[] array) {  
        this.myArray = array.clone();   
    }   
}

(5)在getter方法中,不要直接返回对象本身,而是克隆对象,并返回对象的拷贝

This approach also prevents leakage of the object, preventing members of the object after obtaining a variable inside getter member variables directly by the operation, leading members of the variable is changed.

Finally,
we welcome the exchange, like the point of a praise yo remember the article, thanks for the support!


Guess you like

Origin blog.51cto.com/14442094/2431505