码迷,mamicode.com
首页 > 编程语言 > 详细

java重写equals方法

时间:2016-06-14 10:07:18      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

重写equals: 比较内容。

hashCode: 内容的hashCode()。


/*

* 重写equals必须注意:
* 1 自反性:对于任意的引用值x,x.equals(x)一定为true
* 2 对称性:对于任意的引用值x 和 y,当x.equals(y)返回true,y.equals(x)也一定返回true
* 3 传递性:对于任意的引用值x、y和z,如果x.equals(y)返回true,并且y.equals(z)也返回true,那么x.equals(z)也一定返 回 true
* 4 一致性:对于任意的引用值x 和 y,如果用于equals比较的对象信息没有被修改,
* 多次调用x.equals(y)要么一致地返回true,要么一致地返回false
* 5 非空性:对于任意的非空引用值x,x.equals(null)一定返回false
* 
* 请注意:
* 重写equals方法后最好重写hashCode方法,否则两个等价对象可能得到不同的hashCode,这在集合框架中使用可能产生严重后果
*/


/*
* 1.重写equals方法修饰符必须是public,因为是重写的Object的方法.
* 2.参数类型必须是Object.
*/
public boolean equals(Object other){ //重写equals方法,后面最好重写hashCode方法

if(this == other) //先检查是否其自反性,后比较other是否为空。这样效率高
return true;
if(other == null)
return false;
if( !(other instanceof Cat))
return false;

final Cat cat = (Cat)other;

if( !getName().equals(cat.getName()))
return false;
if( !getBirthday().equals(cat.getBirthday()))
return false;
return true;
}

public int hashCode(){ //hashCode主要是用来提高hash系统的查询效率。当hashCode中不进行任何操作时,可以直接让其返回 一常数,或者不进行重写。
int result = getName().hashCode();
result = 29 * result +getBirthday().hashCode();
return result;
//return 0;
}

 

http://blog.csdn.net/min123456520/article/details/5194030

java重写equals方法

标签:

原文地址:http://www.cnblogs.com/ydxblog/p/5582859.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!