java-如果未覆盖hashCode会发生什么? [英] java - what happens if hashCode is not overriden?

查看:172
本文介绍了java-如果未覆盖hashCode会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
什么是对象哈希码

Possible Duplicate:
what is an objects hashcode

假设我创建了一个名为Employee的对象,该对象具有ID,firstName,lastName和email,用于实例变量和相应的setter/getter方法.如果hashCode()存储在集合对象中时不覆盖Employee对象中的hashCode(),该如何计算?

Let's say that I create an object, called Employee which has id, firstName, lastName and email for instance variables and corresponding setter/getter methods. How is hashCode() calculated if I don't override hashCode() in Employee object when it is stored in collection objects?

推荐答案

如果不重写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.

这篇关于java-如果未覆盖hashCode会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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