简体   繁体   English

Java中的字符串比较和字符串实习

[英]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将在以下情况下起作用:

  • You've already made sure you've got distinct values in some other way (eg you're using string values fetched from a set, but comparing them for some other reason) 您已经确定以其他方式获得了不同的值(例如,您正在使用从集合中获取的字符串值,但出于其他原因进行比较)
  • You know you're dealing with compile-time string constants 你知道你正在处理编译时字符串常量
  • You've manually interned the strings yourself 你自己手动实现了字符串

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM