hashMap怎么保证hash一致性的

  • 作者: 凯哥Java(公众号:凯哥Java)
  • 工作小总结
  • 时间:2018-07-24 13:47
  • 2932人已阅读
简介 学Java的都知道hashMap的底层是“链表散列”的数据结构也也可以说是hash表。在put的实话先根据key的hashcode重新计算hash值的,而我们又知道hash是一种算法。所以哈希码并不是完全唯一的。查看哈希码百科:哈希表可以说就是数组链表,底层还是数组但是这个数组每一项就是一个链表一:为什么说hashmap的put方法是根据key进行hashcode计算的呢?查看源码:在查看hash

🔔🔔好消息!好消息!🔔🔔

 如果您需要注册ChatGPT,想要升级ChatGPT4。凯哥可以代注册ChatGPT账号代升级ChatGPT4

有需要的朋友👉:微信号 kaigejava2022

学Java的都知道hashMap的底层是“链表散列”的数据结构也也可以说是hash表。在put的实话先根据key的hashcode重新计算hash值的,而我们又知道hash是一种算法。所以哈希码并不是完全唯一的。

查看哈希码百科:

哈希表可以说就是数组链表,底层还是数组但是这个数组每一项就是一个链表

一:为什么说hashmap的put方法是根据key进行hashcode计算的呢?

查看源码:

在查看hash方法,如下:

查看putVal方法:

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,

boolean evict) {

Node

[] tab; Node

p; int n, i;

if ((tab = table) == null || (n = tab.length) == 0)

n = (tab = resize()).length;

if ((p = tab[i = (n - 1) & hash]) == null)

tab[i] = newNode(hash, key, value, null);

else {

Node

e; K k;

if (p.hash == hash &&

((k = p.key) == key || (key != null && key.equals(k))))

e = p;

else if (p instanceof TreeNode)

e = ((TreeNode

)p).putTre且还有next。就循环取出进行比较。


TopTop