hashCode() 在 HashSet 或 HashMap 中起什么作用

What is the role played by hashCode() in a HashSet or HashMap

this 个问题的最高投票答案是:

When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.

老实说,我不明白 hashCode() 对于 HashSetHashMap 集合对象的作用是什么。

键对象的hashCode()方法如何用于基于散列的集合中? hashCode() 的对象在其生命周期内发生变化可能是这种情况? 有人可以通过一些例子进一步详细说明这方面吗?

正如此博客 post 中非常清楚地说明的那样,讨论:HashMap 在 Java

中的工作原理

HashMap in Java works on hashing principle. It is a data structure which allows us to store object and retrieve it in constant time O(1) provided we know the key. In hashing, hash functions are used to link key and value in HashMap. Objects are stored by calling put(key, value) method of HashMap and retrieved by calling get(key) method. When we call put method, hashcode() method of the key object is called so that hash function of the map can find a bucket location to store value object, which is actually an index of the internal array, known as the table.

阅读更多:http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html#ixzz42bvBzm6Y