equals || == 小结

来源:互联网 发布:ubuntu ppa是什么 编辑:程序博客网 时间:2024/06/04 21:25
<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());//3537154System.out.println(d1.hashCode());//3537154Integer n1 = new Integer(47);Integer n2 = new Integer(47);System.out.println(n1==n2);//output falseSystem.out.println(n1.equals(n2));//output trueint i = 9;int b = 9;System.out.println(i==b);// output true}}</span>


0 0
原创粉丝点击