Java 为什么需要覆盖Hashmap的hashcode和equals方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18606447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why it is necessary to override hashcode and equals method of key for Hashmap?
提问by Raj
I created a HashMap having Student
as key and String as value.
我创建了一个 HashMapStudent
作为键和字符串作为值。
Now everywhere i have read It is necessary to override equals
and hashcode
method if using as a key for hashmap.
现在我读过的任何地方如果用作哈希图的键,则必须覆盖equals
和hashcode
方法。
But I did not override it. And insert multiple key value pairs in hashmap. I am also able to fetch it back.
但我没有覆盖它。并在hashmap 中插入多个键值对。我也可以把它取回来。
So why it is necessary?
那么为什么有必要呢?
回答by Prasad Kharkar
They are required when you want to use your objects as useful hashing keys into collections that use hashing.
当您想将对象用作有用的散列键到使用散列的集合中时,它们是必需的。
Have your tried to add the Student
objects which are meaningfully equal?
First understand the significance of equals method in java
您是否尝试添加Student
有意义相等的对象?首先了解java中equals方法的意义
Read the significance of equals and hashcode