Comparing java Strings with == [duplicate]

2019-09-21 20:23发布

Possible Duplicate:
Java String.equals versus ==

Is it possible to compare Java Strings using == operator?

Why do I often see, that equals() method is used instead?

Is it because when comparing with literal Strings (like "Hello") using == doesn't imply calling equals()?

11条回答
霸刀☆藐视天下
2楼-- · 2019-09-21 20:41

== operator checks the bit pattern of objects rather than the contents of those objects, but equals function compare the contents of objects.

String str1=new String("abc");
String str2=new String("abc");

System.out.println(str1==str2); will return false because str1 and str2 are different object created with "new" . System.out.println(str1.equals(str2)) will return true because equals() checks for contents of object.

查看更多
姐就是有狂的资本
3楼-- · 2019-09-21 20:52

In Java, you cannot overload operators. The == operator does identity equality. The equals(...) method, on the other hand can be be overridden to do type-specific comparisons.

Here's a code snippet to demonstrate:

String a = "abcdef";
String b = a;
String c = new String(a);

println(a == b); // true
println(a.equals(b)); // true

println(a == c); // false
println(a.equals(c)); // true

The one complication is with equals(...) you need to care about null, too. So the correct null-safe idiom is:

(a == null ? b == null : a.equals(b))

This is a loop you don't have to jump through in say C#

查看更多
唯我独甜
4楼-- · 2019-09-21 20:52

To expand on @amit's answer, the == operator should only be used on value types (int, double, etc.) A String is a reference type and should therefore be compared with the .equals() method. Using the == operator on a reference type checks for reference equality in java (meaning both object references are pointing to the same memory location.)

查看更多
等我变得足够好
5楼-- · 2019-09-21 20:53

No, it's not possible, because with == you compare object references and not the content of the string (for which you need to use equals).

查看更多
Animai°情兽
6楼-- · 2019-09-21 20:53

Operator == compares for string object references ,whereas String.equals method checks for both object references + object values . Moreover , String.equals method inturn uses == operator inside its implementation.

查看更多
祖国的老花朵
7楼-- · 2019-09-21 20:56

== checks if the two objects refer to the same instance of an object, whereas equals() checks whether the two objects are actually equivalent even if they're not the same instance.

查看更多
登录 后发表回答