This question already has answers here:
Why do I need to override the equals and hashCode methods in Java?
(28个答案)
How will Hashmap key behave if hash code is overridden such that it returns only a constant number?
(3个答案)
2年前关闭。
当我在以下语句中使用
我得到这样的输出:
“联系人@ 29453f441”
这对于每个对象都是唯一的。覆盖
(28个答案)
How will Hashmap key behave if hash code is overridden such that it returns only a constant number?
(3个答案)
2年前关闭。
当我在以下语句中使用
hashCode()
方法时:System.out.println(obj.getClass().getName() + "@" +
Integer.toHexString(System.identityHashCode(obj)));
我得到这样的输出:
“联系人@ 29453f441”
这对于每个对象都是唯一的。覆盖
hashCode()
的效果是什么? 最佳答案
您将失去哈希表提供的任何性能,哈希表可以在O(1)时间内从具有不同哈希值的对象中检索集合中的项目,这是我们在使用HashMaps时要实现的目标。
这是另一个问题的引文:
当两个不相等的对象具有相同的哈希值时,这将导致哈希表发生冲突,因为两个对象都希望位于同一插槽(有时称为存储桶)中。
如果您不使用哈希图或其他依赖对象哈希码的算法,则不会造成任何问题。
至于比较,它们将通过equals()
进行区分。
关于java - 如果在覆盖hashCode()函数时返回常量整数会怎样? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42485834/