与==两个字符串的Java比较是假的? [英] Java comparison with == of two strings is false?
问题描述
字符串部分是字符串[6]:
String parts is String[6]:
["231", "CA-California", "Sacramento-155328", "aleee", "Customer Service Clerk", "Alegra Keith.doc.txt"]
但是当我比较部件[0]
带231
:
"231" == parts[0]
上述结果为false,
the above result is false,
我很困惑,所以有人能告诉我原因吗?
I'm confused, so could anybody tell me why?
推荐答案
==
运算符比较对象引用,而不是 String
的值。
The ==
operator compares the object references, not the value of the String
s.
要比较 String
s的值,请使用 String.equals
方法:
To compare the values of String
s, use the String.equals
method:
"231".equals(parts[0]);
对于Java中的任何其他对象都是如此 - 在比较值时,始终使用等于
方法,而不是使用 ==
运算符。
This is true with any other object in Java -- when comparing values, always use the equals
method rather than using the ==
operator.
等于
方法是 对象
,应该被类重写,这些类将以这种或那种方式进行比较。
The equals
method is part of Object
, and should be overridden by classes which will be compared in one way or another.
这篇关于与==两个字符串的Java比较是假的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!