Java探索之旅(12)——equals方法及其覆盖

1.Object中的equals方法

     

   java中的的基本数据类型:byte,short,char,int,long,float,double,boolean。==比较的是值。

    ❶作用:对于复合类型来说,equal判断两个引用变量是否指向同一个对象,即判断地址(等同“==”)。返回true,否则返回false。并没有实际检查是否内容相同。默认实现为:

              public boolean equals(Object obj)
                           {return (this==obj);}

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class Animal{........}  
  2. Animal  animal1=new Dog();  
  3. Animal  animal2=new  Cat();  
  4. Animal  animal3=animal1;  
  5.   
  6. animal1==animal2   (False)  
  7. animal1.equals(animal2)  (False)  
  8.   
  9. animal1==animal3   (True)  
  10. animal1.equals(animal3)   (True)  

    ❷JDK类中有一些类覆盖了Object类的equals()方法。比较规则为:如果两个对象的类型一致且内容一致,则返回true。这些类有:java.io.file,java.util.Date,java.lang.string,包装类(Integer,Double)。
   相反,“==”此时不具备内容比较功能。

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Integer  int1=new Integer(1);  
  2. Integer int2=new Integer(1);  
  3.   
  4. String str1=new String("hello");  
  5. String str2=new String("hello");  
  6.   
  7. int1==int2;//false,不同引用对象  
  8. int1.equals(int2);//TRUE,相同内容  
  9.   
  10. str1==str2;//False,不同引用对象  
  11. str1.equals(str2);//True,相同内容  

   ❸可自定义覆盖object类的equals()方法,重新定义比较规则。

下面Person类的equals()比较规则为:只要两个对象都是Person类,并且他们的属性name都相同,则比较结果为true,否则返回false

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class Person{  
  2.    private String name;  
  3.    Person(String name)   
  4.      {this.name=name;}  
  5.    public boolean equals(Object o){  
  6.      if (this==nullreturn true;  
  7.      else if (!o instanceof Person) return false;  
  8.      final Person other=(Person)o;  
  9.      if (this.name().equals(other.name()))  
  10.        return true;  
  11.      else  
  12.        return false;  
  13.     }  
  14. }  

 注意:在重写equals方法时,要注意满足离散数学上的特性

   ①自反性:对任意引用值X,x.equals(x)的返回值一定为true.
   ②对称性:当且仅当y.equals(x)返回值为true时,x.equals(y)的返回值一定为true;
   ③传递性:如果x.equals(y)=true, y.equals(z)=true,则x.equals(z)=true
   ④一致性:如果参与比较的对象没任何改变,则对象比较的结果也不应该有任何改变
   ⑤非空性:任何非空的引用值X,x.equals(null)的返回值一定为false

2.例子

String s1 = "Monday";
String s2 = "Monday";
s1 == s2;//true
s1.equal(s2);//true

String s1 = "Monday";
String s2 =new Sring( "Monday");
s1 == s2;//false
s1.equal(s2);//true

String s1 = "Monday";
String s2 = new String("Monday");
s2 = s2.intern();
s1 == s2;//true
s1.equal(s2);//true
    




//程序在运行的时候会创建一个字符串缓冲池。当使用 s2 = "Monday" 这样的表达是创建字符串的时候,程序首先会在这个String缓冲池中寻找相同值的对象,在第一个程序///中,s1先被放到了池中,所以在s2被创建的时候,程序找到了具有相同值的 s1将s2引用s1所引用的对象"Monday"

//第二段程序中,使用了 new 操作符,他明白的告诉程序:"我要一个新的!不要旧的!"于是一个新的"Monday"Sting对象被创建在内存中。他们的值相同,但是位置不同。
//intern()检查字符串池里是否存在某个字符串,如果存在,就返回池里的字符串;如果不存在,该方法会将其添加到字符串池中,然后再返回它的引用。



3.if语句下的错误

public class Test {
    public static void main(String[] args) {
        int x;
        boolean setToTen = false;
        if (setToTen) {
            x = 10;
        }
        if (!setToTen) {
            x = 0;
        }
        System.out.println(x);
    }
}

     Java运行报错。此时系统检测不到x初始化,输出报错。尽管我们人为能够看出来。同样的情况出现在两个if下分别return的情况,此时Java也检测不到return语句。应该使用if-else避免这一错误

原文地址:https://www.cnblogs.com/engineerLF/p/5393085.html