String comparison and String interning in Java

你说的曾经没有我的故事 提交于 2019-11-26 03:44:42

问题


When should one compare Strings as objects and when should one use their equals method? To make sure, I always use equals, but that doesn\'t seem very efficient. In what situations can I be certain that string1 == string2 is a safe to use?

Thanks!


回答1:


You should almost always use equals. You can be certain that string1 == string2 will work if:

  • You've already made sure you've got distinct values in some other way (e.g. 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.




回答2:


From what I know of Java, string1==string2 will only be true if the references to those objects are the same. 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



回答3:


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. You could be certain that a comparison would be between the same object.

Stick with the equals for string comparison.



来源:https://stackoverflow.com/questions/3885753/string-comparison-and-string-interning-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!