equals()方法和“==”运算符

超类object中的比较

超类Object中有这个equals()方法,该方法主要用于比较两个对象是否相等。该方法的源码以下:java

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

equals()方法和“==”运算符比较

首先笼统的来说 “java中equals()方法和“==”运算符” 都是比较的地址,那为何咱们在使用中总会出现混淆的状况呢总是弄错呢,这是由于“重写equals()方法”和一些 “特殊状况”的存在。this

对于字符串变量来讲,使用“==”和“equals()”方法比较字符串时,其比较方法不一样。

  • “==”比较两个变量自己的值,即两个对象在内存中的首地址。
  • “equals()”比较字符串中所包含的内容是否相同。
public class Tets {
    public static void main(String[] args) {
        String s1 = new String("abc");
        String s2 = new String("abc");
        System.out.println(s1==s2);
        System.out.println(s1.equals(s2));
        StringBuffer s3 = new StringBuffer("abc");
        StringBuffer s4 = new StringBuffer("abc");
        System.out.println(s3==s4);
        System.out.println(s3.equals(s4));
    }
}

输出结果code

false
true
false
false

按照全部类都是继承超类object,超类object中的equals方法比较的是地址,为何string类却不是在比较地址呢,就是由于string类中发生了equals重写。对象

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String) anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                            return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

在stringbuffer类中没有对equals方法重写,因此结果是false,请看stringbuffer中的equals方法。继承

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

stringbuffer的比较咱们能够获取string对象之后再进行比较内存

s3.toString().equals(s4.toString());

对于非字符串变量来讲,"=="和"equals"方法的做用是相同的都是用来比较其对象在堆内存的首地址,即用来比较两个引用变量是否指向同一个对象。

public class Tets {
    public static void main(String[] args) {
        Tets tets = new Tets();
        Tets tetsb = new Tets();
        tets.equals(tetsb);
    }
}

equals文档

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

注意

若是是基本类型比较,那么只能用==来比较,不能用equals字符串

对于基本类型的包装类型,好比Boolean、Character、Byte、Shot、Integer、Long、Float、Double等的引用变量,==是比较地址的,而equals是比较内容的。get

public class Tets {
    public static void main(String[] args) {
        Integer n1 = new Integer(30);
        Integer n2 = new Integer(30);
        Integer n3 = new Integer(31);
        System.out.println(n1 == n2);//结果是false 两个不一样的Integer对象,故其地址不一样,
        System.out.println(n1 == n3);//那么无论是new Integer(30)仍是new Integer(31) 结果都显示false
        System.out.println(n1.equals(n2));//结果是true 根据jdk文档中的说明,n1与n2指向的对象中的内容是相等的,都是30,故equals比较后结果是true
        System.out.println(n1.equals(n3));//结果是false 因对象内容不同,一个是30一个是31
    }
}

参考 https://mp.weixin.qq.com/s/wH-SCnYqJBK5MPe7jOisTQ源码

相关文章
相关标签/搜索