1. 程式人生 > >Java比較String ==和equals() 解析

Java比較String ==和equals() 解析

先看一個例子 equals() 比較String

public class TestString {

    public static void main(String[] args) {
        String strOne = "testString";
        String strTwo = "testString";
        System.out.println(strOne.equals(strTwo));
    }
}

結果為:true

再看 == 比較String

public class TestString {

    public
static void main(String[] args) { String strOne = "testString"; String strTwo= "testString"; System.out.println(strOne == strTwo); } }

結果為:true

分析原因:

String的equals()是比較字串的內容。故第二個true很容易理解,因為strOne 和strTwo的內容顯然相同。

==是比較記憶體地址的,第一個true說明strOne 和strTwo的地址相同。
為什麼呢?

java有常量池,儲存所有的字串常量。

String strOne = “testString”
java首先會在常量池查詢是否有 “testString”這個常量,發現沒有,於是建立一個 “testString”,然後將其賦給strOne。

String strTwo= “String”;
java同樣會在常量池中查詢 “testString”,這次常量池中已經有strOne 建立的 “testString”,故不建立新的常量,將其地址賦給strTwo。

如此,strOne和strTwo便有了相同的地址。

用String() 來建立String物件

public class TestString {

    public
static void main(String[] args) { String strOne = "testString"; String strThree = new String("testString"); System.out.println(strOne==strThree); System.out.println(strOne.equals(strThree)); } }

結果為:
false
true

public class TestString {

    public static void main(String[] args) {
        String strOne = new String("testString");
        String strThree = new String("testString");
        System.out.println(strOne == strThree);
        System.out.println(strOne.equals(strThree));
    }
}

結果相同:
false
true

分析原因:

而用new String(“testString”)建立的兩個字串,用equals()比較相等,用==比較則不相等。

為什麼呢?

new String()每次會在堆中建立一個物件,每次建立的物件記憶體地址都不同,故==不相等。但字串內容是相同的,故equals()相等。

再看關於普通類的

public class TestString {

    public static void main(String[] args) {
        Person perOne = new Person();
        Person perTwo = new Person();
        System.out.println(perOne == perTwo);
    }
}

class Person {

}

結果為flase

大家都知道,java中一般不用==比較兩個物件,而是用equals()

給Person類一個域 id,複寫equals()

public class TestString {

    public static void main(String[] args) {
        Person perOne = new Person(123);
        Person perTwo = new Person(123);
        System.out.println(perOne.equals(perTwo));
    }
}

class Person {
    private int id;

    Person(int id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Person)) {
            return false;
        }
        Person p = (Person) o;
        return p.id == id;
    }

}

結果為:true