为什么我们不能使用(==)代替.equals()方法来比较字符串对象?

huangapple go评论87阅读模式
英文:

Why can't we use (==) instead of .equals() methods to compare string objects?

问题

Box b1 = new Box();
Box b2 = b1;

这里,b1 和 b2 引用同一个对象。因此,在两个字符串对象的情况下,为什么不能使用 == 运算符来比较它们,而不是使用 .equals() 方法呢?

英文:
Box b1 = new Box();
Box b2 = b1;

Here b1 and b2 refers to same object. So in case of 2 String objects why can't we use == to compare them instead of .equals() methods.

答案1

得分: 6

没什么实质区别。当你使用 == 来比较对象时,你比较的是它们的内存地址,而不是它们的值。在你的例子中,执行 b1 == b2 会返回 true,因为它们是同一个对象。然而,如果你改为:

Box b1 = new Box();
Box b2 = new Box();

现在如果你用 == 来比较它们,尽管这些对象完全相同,它会返回 false。对于字符串也是一样的。

英文:

There is no difference really. When you use == to compare objects, you're comparing their memory addresses, not their values. In your example, doing b1 == b2 will return true because they are the same object. However if you instead did:

Box b1 = new Box();
Box b2 = new Box();

Now if you compare them with == it will return false despite the fact that the objects are exactly the same. Same goes for Strings.

答案2

得分: 2

"=="比较的是对象引用本身,而不是它们的字面值。如果两个变量指向同一个对象,它将返回true。
因此,

String s1 = new String("hello");
String s2 = new String("hello");

在这里,
s1==s2将返回false,因为它们是不同的对象。

当你使用equals()时,它会比较内容的字面值并给出结果。

英文:

"==" compares Object references with each other and not their literal values. If both the variables point to same object, it will return true.
So,

String s1 = new String("hello");
String s2 = new String("hello");

Here
s1==s2, will return false as both are different objects.

When you use equals(), it will compare the literal values of the content and give its results.

答案3

得分: 1

== 比较内存地址,而 .equals() 比较值

String s1 = new String("HELLO");
String s2 = new String("HELLO");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));

输出:

False

True

英文:

== Compares memory address while .equals() compares the values

    String s1 = new String("HELLO"); 
    String s2 = new String("HELLO"); 
    System.out.println(s1 == s2); 
    System.out.println(s1.equals(s2));

Output:

False

True

huangapple
  • 本文由 发表于 2020年4月4日 13:23:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/61024135.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定