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?
-
3String.equals() is efficient. The first thing checked is if string1 == string2. (Actually Object.equals() checks this.)Skip Head– Skip Head2010-10-07 21:01:26 +00:00Commented Oct 7, 2010 at 21:01
-
But of course! How stupid of me. It's a very obvious thing to do. And highly efficient one as you say. Never though of it. Shame on me! Thanks!Albus Dumbledore– Albus Dumbledore2010-10-07 21:26:45 +00:00Commented Oct 7, 2010 at 21:26
Add a comment
|
3 Answers
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 Comments
DJClayworth
Absolutely the right answer. Using '==' because equals() is inefficient is a great example of premature optimization.
Darron
And String.intern() is slow enough to be useless for performance in most cases.
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
7 Comments
sepp2k
The first comparison will not be false because they are not separate objects. String literals are interned in Java.
stratwine
The first comparison should return false in this case- String string1 = new("Bob"); String string2 = new("Bob");
Anthony
I'll edit my responce to make it more clearly defined. I thought I might run into this issue with Java.
Dirk
@stratwine: No, this is not true. See java.sun.com/docs/books/jls/third_edition/html/…: Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern.
DJClayworth
The answer is correct, and the first comparison is 'false'. "new String(...)" creates (surprise surprise) a new String, which is not the same object as the interned "Bob".
|