一般來說equals()
和"=="
運算符是用來比較兩個對象是否相等,但是這兩者之前還是有許多不同:
- 最主要的不同是
.equals()
是方法,==
是運算符。 - 使用
==
來進行引用的比較,指的是是否指向同一內存地址。使用.equals()
來進行對象內容的比較,比較值。 - 如果沒有重寫
.equals
就會默認調用最近的父類來重寫這個方法。 - 示例代碼:
// Java program to understand
// the concept of == operator
public class Test {
public static void main(String[] args)
{
String s1 = new String("HELLO");
String s2 = new String("HELLO");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}
}
輸出:
false
true
解釋: 這裏我們創建了兩個對象分別命名爲s1
和s2
。
s1
和s2
是指向不同對象的引用。- 當我們使用
==
來比較s1
和s2
時,返回的是false
,因爲他們所佔用的內存空間不一樣。 - 使用
.equals()
時,因爲只比較值,所以結果時true
。
我們來分別理解一下這兩者的具體區別:
等於運算符(==)
我們可以通過==
運算符來比較每個原始類型(包括布爾類型),也可以用來比較自定義類型(object types)
// Java program to illustrate
// == operator for compatible data
// types
class Test {
public static void main(String[] args)
{
// integer-type
System.out.println(10 == 20);
// char-type
System.out.println('a' == 'b');
// char and double type
System.out.println('a' == 97.0);
// boolean type
System.out.println(true == true);
}
}
輸出:
false
false
true
true
如果我們使用==
來比較自定義類型,需要保證參數類型兼容(compatibility)(要麼是子類和父類的關係,要麼是相同類型)。否則我們會產生編譯錯誤。
// Java program to illustrate
// == operator for incompatible data types
class Test {
public static void main(String[] args)
{
Thread t = new Thread();
Object o = new Object();
String s = new String("GEEKS");
System.out.println(t == o);
System.out.println(o == s);
// Uncomment to see error
System.out.println(t==s);
}
}
輸出:
false
false
// error: incomparable types: Thread and String
.equals()
在Java中,使用equals()
對於String
的比較是基於String
的數據/內容,也就是值。如果所有的他們的內容相同,並且都是String
類型,就會返回true
。如果所有的字符不匹配就會返回false
。
public class Test {
public static void main(String[] args)
{
Thread t1 = new Thread();
Thread t2 = new Thread();
Thread t3 = t1;
String s1 = new String("GEEKS");
String s2 = new String("GEEKS");
System.out.println(t1 == t3);
System.out.println(t1 == t2);
System.out.println(t1.equals(t2));
System.out.println(s1.equals(s2));
}
}
輸出:
true
false
false
true
解釋:這裏我們使用.equals
方法去檢查是否兩個對象是否包含相同的值。
- 在上面的例子中,我們創建來3個線程對象和兩個字符串對象。
- 在第一次比較中,我們比較是否
t1==t3
,衆所周知,返回true的原因是因爲t1和t3是指向相同對象的引用。 - 當我們使用
.equals()
比較兩個String
對象時,我們需要確定兩個對象是否具有相同的值。 String
"GEEKS"
對象包含相同的“GEEK”
,所以返回true
。
本文作者:Bishal Kumar Dubey
譯者:xiantang
原文地址:Difference between == and .equals() method in Java