在看equals方法时遇到一个小的问题,这里写出来与大家分享,equals方法如果这样用的话:
public class maintest {
/**
* @param args
*/
public static void main(String[] args) {
Cat cat1 = new Cat(1,2,3);
Cat cat2 = new Cat(1,2,3);
System.out.println(cat1.equals(cat2));
}
}
class Cat{
int color;
int height,weight;
public Cat(int color,int height,int weight){
this.color = color;
this.height = height;
this.weight = weight;
}
}
这样的话结果为 false ,这是为什么呢?分析一下内存,答案很明显,假设cat1指向内存是A1,cat2指向的内存A2,其实equals比较的是内存,这是两个不同的引用,所以答案为false。但是Integer new 一个对象的话就可以比较,这是由于Integer对象对equals方法进行了重写,所以我们也可以对equals方法进行重写:
public class maintest {
/**
* @param args
*/
public static void main(String[] args) {
Cat cat1 = new Cat(1,2,3);
Cat cat2 = new Cat(1,2,3);
System.out.println(cat1.equals(cat2));
}
}
class Cat{
int color;
int height,weight;
public Cat(int color,int height,int weight) {
this.color = color;
this.height = height;
this.weight = weight;
}
public boolean equals(Object object){
if (object==null) return false;
else{
if(object instanceof Cat){
Cat cat = (Cat)object;
if(cat.color == this.color && cat.height == this.height && cat.weight == weight)
return true;
else {
return false;
}
}
}
return false;
}
}
这样我们对equals方法进行重写,进而可以对我们想要比较的内容进行比较。