Object中的equal()方法详细与"=="

之前一直有点模糊的概念 equal()与==方法的区别!
package com.yangfan.equal;

public class Testequal {
	public static void main(String args[]) {
		Cat cat1 = new Cat(1, 2, 3);
		Cat cat2 = new Cat(1, 2, 3);

		System.out.println(cat2 == cat1);//本质上比较是比较内堆内存的指向引用是否相同!永远是false
		System.out.println(cat2.equals(cat1));//在没有重写equal()方法之前:false,本质上也是调用了==来比较!
		                                       //重写equal()后是:true;
		System.out.println("----------------");

		String s1 = new String("hello");
		String s2 = new String("hello");
		System.out.println(s2 == s1);//这个是指引用结果是:永远是false
		System.out.println(s2.equals(s1));//String 重写了equal()方法:true;默认重写Date类s
	}
}

class Cat {
	private int color, height, weight;

	public Cat() {
	}

	public Cat(int color, int height, int weight) {
		super();
		this.color = color;
		this.height = height;
		this.weight = weight;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + color;
		result = prime * result + height;
		result = prime * result + weight;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final Cat other = (Cat) obj;
		if (color != other.color)
			return false;
		if (height != other.height)
			return false;
		if (weight != other.weight)
			return false;
		return true;
	}

}


 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值