且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

java-如果未覆盖hashCode会发生什么?

更新时间:2023-02-05 21:49:12

如果不重写hashcode(),那么集合将使用Object类中的默认实现.即使根据equals()方法它们相等,此实现也会为不同的对象提供不同的值.

If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.

某些集合,例如HashSet,HashMap或HashTable,使用哈希码存储其数据并进行检索.如果未以一致的方式实现hashcode()和equals(),则它们将无法正常运行.

Some collections, like HashSet, HashMap or HashTable use the hash code to store its data and to retrieve it. If you don't implement hashcode() and equals() in a consistent manner, then they will not function properly.

按照 Javadoc :Object.hashcode()通常通过将对象的内部地址转换为整数来实现,但是Java(TM)编程语言不需要此实现技术".因此,我建议不要依赖特定的实现.有关实现的实际作用,请参见此答案(针对类似问题).

As per Javadoc: Object.hashcode() is ''typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java(TM) programming language''. Therefore I would advise not to rely on a specific implementation. For what the implementations really do, see this answer to a similar question.