Object对象之equals方法

在看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方法进行重写,进而可以对我们想要比较的内容进行比较。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值