为什么要重写equals方法:
默认equals在比较两个对象时,是看他们是否指向同一个地址的。
但有时,我们希望两个对象只要是某些属性相同就认为他们的quals为true。
方法一
public class TestEquals {
public static void main(String[] args) {
// TODO Auto-generated method stub
Cat c1=new Cat(1,2,3);
Cat c2=new Cat(1,2,3);
System.out.println(c1==c2);
System.out.println(c1.equals(c2));
}
}
class Cat{
int color;
int height;
int weight;
public Cat(int color,int height,int weight) {
this.color=color;
this.height=height;
this.weight=weight;
}
public boolean equals(Object obj) {
if(obj==null)
return false;
else {
if(obj instanceof Cat) {
Cat c=(Cat)obj;
if(c.color==this.color&&c.height==this.height&&c.weight==this.weight)
return true;
}
}
return false;
}
}
在上面的例子中,如果不写equals方法,打印出来的都是false,跟实际不符。
instanceof操作符的解释
instanceof 是一个运算符, 用于判断一个对象是不是属于一个类 当左边是右边的一个对象时 返回true ; if在这是用于判断你传入的对象是否是Person类的对象,如果不是就不用运行下面的代码,不是同一类对象无法比较!如果不判断,当其他类对象时,编译不会报错,运行会出错ClassCastException ,因为不是Cat类,Cat p = (Cat)obj,向下转型失败
每个覆盖了equals方法的类中,也必须覆盖hashCode方法。
如果不这样的话,就会违反Object.hashCode的通用约定,从而导致该类无法结合所有基于散列的集合一起正常运作,这样的集合包括HashMap、HashSet和Hashtable。
在引用程序的执行期间,只要对象的equals方法的比较操作所用到的信息没有被修改,那么对这同一个对象调用多次,hashCode方法都必须始终如一的返回同一个整数。在一个应用程序的多次执行过程中,每次执行所返回的整数可以不一致。
如果两个对象根据equals方法比较是相等的,那么调用这两个对象中任意一个对象的hashCode方法都必须产生同样的整数结果。
如果两个对象根据equals方法比较是不相等的,那么调用这两个对象中任意一个对象的hashCode方法,则不一定要蚕声不同的整数结果。但是程序员应该知道,给不相等的对象产生截然不同的整数结果,有可能提高散列表(hash table)的性能。(比如,当你一个entity只根据id比较是否相等,但是在没实例化之前,没有id数值,那么默认的equals返回false,但是hashCode返回的值却相等。)
方法二
public class TestEquals {
public static void main(String[] args) {
// TODO Auto-generated method stub
Cat c1=new Cat(1,2,3);
Cat c2=new Cat(1,2,3);
System.out.println(c1==c2);
System.out.println(c1.equals(c2));
}
}
class Cat{
int color;
int height;
int weight;
public Cat(int color,int height,int weight) {
this.color=color;
this.height=height;
this.weight=weight;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + color;
result = prime * result + height;
result = prime * result + weight;
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cat other = (Cat) obj;
if (color != other.color)
return false;
if (height != other.height)
return false;
if (weight != other.weight)
return false;
return true;
}
}