equals || == 小结

<span style="font-size:14px;">Note:</span>
<span style="font-size:14px;">one:The <code>equals</code> method for class <code>Object</code> implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values <code>x</code> and  <code>y</code>, this method returns <code>true</code> if and only if <code>x</code> and <code>y</code> refer to the same object (<code>x == y</code> has the value <code>true</code>).当我们比较对象时,常用他们的引用来比较,用equals 方法就能够比较,不过当且仅当这两个引用指向同一个对象时才返回true。</span>
<span style="font-size:14px;">two:equals 用来比较对象的内容,== 用来比较引用。</span>
<span style="font-size:14px;">three:equals 方法基本类型不适用基本类型:int ,char, byte,short,long, float,double,void ,boolean。直接用== 就可以判断了</span>
import java.util.*;

<span style="font-size:14px;">class Dog{
	private String name;
	private String says;
	Dog(String name,String says){
		this.name = name;
		this.says = says;
	}
	public boolean equals(Object obj){
		return obj instanceof Dog && name==((Dog)obj).name && ((Dog)obj).says == says;
	}
	public int hashCode(){
		return name.hashCode();
	}
}
public class TestEquals {
	public static void main(String []args){
		
		Dog d1 = new Dog("spot","Ruff");
		Dog d2 = new Dog("spot","Ruff");
		System.out.println(d1==d2);// output false;
		System.out.println(d1.equals(d2));// output true; 因为重写了equals 方法。
		System.out.println(d2.hashCode());//3537154
		System.out.println(d1.hashCode());//3537154
		
		Integer n1 = new Integer(47);
		Integer n2 = new Integer(47);
		System.out.println(n1==n2);//output false
		System.out.println(n1.equals(n2));//output true
		
		int i = 9;
		int b = 9;
		System.out.println(i==b);// output true
	}
	
}
</span>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值