面试遇到的问题3
来源:1-1 周介绍
何艾莉
2022-09-29 15:11:49
老师好,hashMap与hashTable用的hashCode一致吗?如果不一致,他们分别是怎样的?
1回答
好帮手慕小蓝
2022-09-29
同学你好,HashMap与Hashtable用的hashCode是不一致的。
HashMap使用了父类AbstractMap中的hashCode方法,而其中需要调用内部接口实现的hashCode方法。
源码如下:
HashMap中的hashCode:
AbstractMap:
public int hashCode() { int h = 0; for (Entry<K, V> entry : entrySet()) h += entry.hashCode(); return h; }
Node:
public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); }
Hashtable中的hashCode:
public synchronized int hashCode() { int h = 0; if (count == 0 || loadFactor < 0) return h; // Returns zero loadFactor = -loadFactor; // Mark hashCode computation in progress Entry<?,?>[] tab = table; for (Entry<?,?> entry : tab) { while (entry != null) { h += entry.hashCode(); entry = entry.next; } } loadFactor = -loadFactor; // Mark hashCode computation complete return h; }
两者在算法有本质的区别,建议同学自行在网上搜索两者算法上知识。该部分涉及的知识量很大,老师这里无法为同学做简要的解答。
祝学习愉快~
相似问题