栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

HashMap,你是怎么做到的Key重复?,Java高级工程师进阶学习—Java热修复原理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

HashMap,你是怎么做到的Key重复?,Java高级工程师进阶学习—Java热修复原理

public static void main(String[] args) {

Student student1 = new Student(1,“小朱”);

Student student2 = new Student(2,“大牛”);

HashMap hashMap = new HashMap<>();

hashMap.put(student1,“菜鸡”);

hashMap.put(student2,“大神”);

//这个方法不需要穿Student,为了验证是同一个对象所以改动了一下

updatevalue(hashMap,student1);

System.out.println(hashMap.size());

}

public static HashMap updatevalue(HashMap hashMap,Student student){

Student student1 = new Student(1,“小朱”);

System.out.println(student1.equals(student));

hashMap.put(student1,“新手”);

return hashMap;

}

}

复制代码

运行结果

true

3

复制代码

小朱: 代码就是这样,为了验证这个两个对象是相同的,我该遭了updatevalue方法.本来只要传HashMap,为了验证我外加了一个Student.

大牛: 哦,确实有意思,你怎么不尝试写个取出元素的方法,例如:

getValue

public static void getValue(HashMap hashMap){

Student student1 = new Student(1,“小朱”);

System.out.println(hashMap.get(student1));

}

复制代码

小朱: 我试下.

输出结果

null

复制代码

小朱: 为什么?我重写了equals它们对象都相等啊?为什么取不出来!

大牛: HashMap源码了解一下.

public V put(K key, V value) {

return putVal(hash(key), key, value, false, true);

}

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).putTreeval(this, tab, hash, key, value);

else {

for (int binCount = 0; ; ++binCount) {

if ((e = p.next) == null) {

p.next = newNode(hash, key, value, null);

if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st

treeifyBin(tab, hash);

break;

}

if (e.hash == hash &&

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

break;

p = e;

}

}

if (e != null) { // existing mapping for key

V oldValue = e.value;

if (!onlyIfAbsent || oldValue == null)

e.value = value;

afterNodeAccess(e);

return oldValue;

}

}

++modCount;

if (++size > threshold)

resize();

afterNodeInsertion(evict);

return null;

}

复制代码

大牛: 还有下面这段.

public static void main(String[] args) {

Student student1 = new Student(1,“小朱”);

Student student2 = new Student(1,“小朱”);

System.out.println(student1.equals(student2));

System.out.println(student1.hashCode());

System.out.println(student2.hashCode());

}

复制代码

小朱: 我跑一下看看.

true

1456208737

288665596

复制代码

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/658827.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号