为什么必须重写Hashmap的哈希码和equals方法? [英] Why it is necessary to override hashcode and equals method of key for Hashmap?

查看:118
本文介绍了为什么必须重写Hashmap的哈希码和equals方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个以 Student 作为键,并将String作为值的HashMap。

I created a HashMap having Student as key and String as value.

现在我到处都读过它如果用作哈希图的键,则必须重写 equals hashcode 方法。

Now everywhere i have read It is necessary to override equals and hashcode method if using as a key for hashmap.

但是我没有覆盖它。并在哈希图中插入多个键值对。
我也可以将其取回。

But I did not override it. And insert multiple key value pairs in hashmap. I am also able to fetch it back.

那为什么有必要?

推荐答案

当您要将对象用作使用哈希的集合中的有用哈希键时,它们是必需的。

They are required when you want to use your objects as useful hashing keys into collections that use hashing.

您是否尝试过添加有意义的 Student 对象?
首先了解

Have your tried to add the Student objects which are meaningfully equal? First understand the significance of equals method in java

阅读等于和哈希码的重要性

这篇关于为什么必须重写Hashmap的哈希码和equals方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆