[英]String comparison and String interning in Java
When should one compare String
s as objects and when should one use their equals
method? 应该何时将
String
作为对象进行比较,何时应该使用equals
方法? To make sure, I always use equals
, but that doesn't seem very efficient. 为了确保,我总是使用
equals
,但这似乎不是很有效。 In what situations can I be certain that string1 == string2
is a safe to use? 在什么情况下我可以确定
string1 == string2
是否可以安全使用?
Thanks! 谢谢!
You should almost always use equals
. 你应该几乎总是使用
equals
。 You can be certain that string1 == string2
will work if: 您可以确定
string1 == string2
将在以下情况下起作用:
It really doesn't happen very often, in my experience. 根据我的经验,它确实不会经常发生。
From what I know of Java, string1==string2
will only be true if the references to those objects are the same. 根据我所知的Java,如果对这些对象的引用相同,则
string1==string2
将为true。 Take a look at the following case 看看以下案例
String string1 = new String("Bob");
String string2 = new String("Bob");
string1 == string2; // false, they are seperate objects
string1 = string2; // asigning string1 to string2 object
string1 == string2; // true, they both refer to the same object
You can only use the ==
for comparison if you are sure the objects are the same. 如果您确定对象是相同的,则只能使用
==
进行比较。
For example, this could occur if you had a final static String variable. 例如,如果您有一个最终的静态String变量,则可能会发生这种情况。 You could be certain that a comparison would be between the same object.
您可以确定在同一对象之间进行比较。
Stick with the equals
for string comparison. 坚持
equals
字符串比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.