与==两个字符串的Java比较是假的?

Java comparison with == of two strings is false?

本问题已经有最佳答案,请猛点这里访问。

字符串:字符串的配件是[ 6 ]

1
["231","CA-California","Sacramento-155328","aleee","Customer Service Clerk","Alegra Keith.doc.txt"]

但当我parts[0]:比较与"231"

1
"231" == parts[0]

上面的结果是false,

我很困惑,为什么人可以告诉我吗?


(P)The EDOCX1 Emocx1 Nico operator compars the object references,not the value of the EDOCX1.(p)(P)为了比较EDOCX1的标价,使用EDOCX1标语5。(p)字母名称(P)This is true with any other object in Java--When comparing values,always use the EDOCX1 penogical 6(p)(P)The EDOCX1 6 universal method is part of EDOCX1 welcome 9,and should be overridden by classes which will be compared in one way or another.(p)


(P)If the strings are not interned,they=-checks reference identity.使用:(p)字母名称(P)敦促。(p)


(P)EDOCX1 Eno In Java Compares the Address of the Objects(Strings in this case).(p)(P)你想要的是什么?(p)


(P)The following prints out"true";(p)字母名称(P)这是因为Strings are not mutatible and Java will try and save as much space as possible,so it points both to the same memory reference.(p)(P)However,the following prints out"fals":(p)字母名称(P)EDOCX1 12 will force it to store the string in a new memory location.(p)(P)by the way,you should always use EDOCX1 English 13 to compare strings(for cases just like this one)(p)


(P)使用平等方法:缔约方[0]、平等[231]。=Operator compars object references.(p)


(P)"=Compares object references,in your case"231"is a different object than parts[0].(p)(P)You want to use string.equals.(p)字母名称


(P)The answer is very simple:When you compare strings through==-operator,you actually compare if two different variables refer to a single string object.and they don't,the string in the array and newly created"231"are different string objects with the same contents.(p)(P)The right thing to do is to use the following expression:EDOCX1 universal 10 or EDOCX1如果这些目标包含在同一价值中,这将使你得到你需要的东西并回到现实中。(p)


(P)You may also use comparto(string)method:(p)字母名称


(P)I thought it might be helpful to express the answer in a test case:(p)字母名称


(P)这是真正的好例子。The'=Operator with string can be really tricky in Java.(p)字母名称(P)Which will produce following output:(p)字母名称


(P)利用平等方法比较目标:(p)字母名称(P)The comparison'=compars references,not values.(p)


(P)As many others have already explained,you try to compare with equality operator,but then it would relies on object.equals(……)instead of string.equals(……)。(p)(P)So you can do the job by explicitly calling string.equals(),but instead of writing(p)字母名称(P)I would prefer such:(p)字母名称(P)As it avoids testing potential nullity of parts[0](but be careful that parts variable itself could be null…)(p)(P)Another way is using string.intern():(p)字母名称(P)见http://java.sun.com/j2se/1.4.2/docs/api/java/lang/string.html/;intern(……)for more info on that.(p)