您的位置:首页 > 编程语言 > Java开发

Java 重写equals()时为什么要重写hashCode()方法

2018-04-04 21:35 621 查看
答案在基类Object中,你找到了吗?

package java.lang;

/**
* Class {@code Object} is the root of the class hierarchy.
* Every class has {@code Object} as a superclass. All objects,
* including arrays, implement the methods of this class.
*
* @author  unascribed
* @see     java.lang.Class
* @since   JDK1.0
*/
public class Object {

...
/**
* ...
* Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.
*
* @param   obj   the reference object with which to compare.
* @return  {@code true} if this object is the same as the obj
*          argument; {@code false} otherwise.
* @see     #hashCode()
* @see     java.util.HashMap
*/
public boolean equals(Object obj) {
return (this == obj);
}
...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: