Difference between String.isEmpty() and String.equals("")
I created a "Color Chooser" with three textboxes where the user defines rgb values.
To check if values entered are correct (only numbers between 0-255) I'm using the following:public Color getColor() {
if (tfRed.getText().equals("") || tfGreen.getText().equals("") || tfBlue.getText().equals("")) {
return new Color(0, 0, 0, 0);
} else {
if (tfRed.getText().matches("\\d+") && tfGreen.getText().matches("\\d+") && tfBlue.getText().matches("\\d+")) {
// ...
} else {
return new Color(0, 0, 0, 0);
}
}
}
What I'm asking: is it better to use String.isEmpty()
? I never found a satisfying answer and I've always wondered i开发者_如何学Pythonf there is any difference.
I think isEmpty()
is a bit more efficient. However a smart compiler may optimize the equals("")
call anyway. From the OpenJDK source:
671 public boolean isEmpty() {
672 return count == 0;
673 }
1013 public boolean equals(Object anObject) {
1014 if (this == anObject) {
1015 return true;
1016 }
1017 if (anObject instanceof String) {
1018 String anotherString = (String)anObject;
1019 int n = count;
1020 if (n == anotherString.count) {
1021 char v1[] = value;
1022 char v2[] = anotherString.value;
1023 int i = offset;
1024 int j = anotherString.offset;
1025 while (n-- != 0) {
1026 if (v1[i++] != v2[j++])
1027 return false;
1028 }
1029 return true;
1030 }
1031 }
1032 return false;
1033 }
Also the answer here on whether to use str.isEmpty()
or "".equals(str)
is spot on:
The main benefit of
"".equals(s)
is you don't need the null check (equals
will check its argument and returnfalse
if it's null), which you seem to not care about. If you're not worried abouts
being null (or are otherwise checking for it), I would definitely uses.isEmpty()
; it shows exactly what you're checking, you care whether or nots
is empty, not whether it equals the empty string
Yes, use String.isEmpty()
. It is cleaner (semantically) (performance is also slightly better, but that would be unnoticable) If the instance can be null, use commons-lang StringUtils.isEmpty(string)
Since isEmpty()
checks if the length of the String
is 0 and ""
is the only String
with length 0, each String
for which isEmpty()
returns true
would also return true
to .equals("")
. So technically, they do the same thing.
There might be a minimal difference in performance, but I wouldn't bother about that at all (I'd be very surprised if it were noticeable in production code).
Another difference is if you wrote "".equals(someString)
, then it would be "null
-safe". In other words: if someString
was null
, this construct would simply evaluate to false
and not throw a NullPointerException
. If, however, you have someString.equals("")
then this would not apply.
The most important difference is how it's read: isEmpty()
makes the intention very clear: you want to treat empty strings differently. .equals("")
is ever so slightly less clear ("if that string equals that other string, that happens to be empty").
Typically, I like to use equals but in reverse, ie:
"".equals(someString);
Null-safe :)
But yeah, isEmpty() is a simpler operation but not so much that I see it making any significant performance contribution (unless you are writing embedded real-time stuff).
With myString.equals("")
, first the compiler creates an String object (it is equivalent to myString.equals(new String(""))
.
So, isEmpty() should be a better option (although equals("") is very popular).
In theory, it is. For isEmpty()
, only the internal metadata of the string has to be looked at (e.g., it's length). For the comparison, you would expect slightly more case differentiations happening.
In practice, it does not matter. You would not observe the speed difference.
Rule of thump: Use the method that is best understood / most readable by the programmer. If it is a test for empty string, I think isEmpty()
fits that purpose best.
isEmpty()
is faster because it only compares the length
integer field in String
class to 0
while comparing to an empty string will at best compare references (similar speed) and at worst - run a loop with 0 iterations.
But the biggest difference is readability - isEmpty()
is shorter and easier to grasp. BTW I wish there was an isBlank()
shorthand for .trim().isEmpty()
...
One more reason using myString.equals("")
or myString.length() == 0
is that String#isEmpty()
method was introduced in Java 1.6.
So arguments to do not use String#isEmpty()
can be compatibility reasons with previous versions of Java.
It's partly a matter of history and legacy uses. isEmpty()
was only added in JDK 6:
/**
* Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
*
* @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
* <tt>false</tt>
*
* @since 1.6
*/
public boolean isEmpty() {
Before that, everyone compared with ""
to see if an String was empty or not. Old habits die hard, so loads of people keep using the ""
comparison.
Of course, as mentioned by someone else already, if you use "".equals(someString)
then it's automatically null safe. Many people combine the idea of isEmpty with null safeness, by making a static isEmpty method.
isEmpty
was only introduced in 1.6. Check Since tag in javadoc.
Therefore, if you are compiling for 1.5 and lower equals("")
is your only choice.
However, if version compatibility is not of your concern, I would use isEmpty
. As Bozho pointed out it is semantically cleaner ( and a bit faster ).
I had always used .isEmpty()
... until today, when I discovered that it does not exist in Java 5.
So :
- In Java 6 and newer, we have the choice, and I recommend using
.isEmpty()
, it is easier to write and clearer to read. - In Java 5 and older we have to use
.equals("")
.
String.equals("") is bit slower than just an isEmpty() call. Strings store a count variable initialized in the constructor, since Strings are immutable.
isEmpty() compares the count variable to 0, while equals will check the type, string length, and then iterate over the string for comparison if the sizes match.
So to answer your question, isEmpty() will actually do a lot less! and that's a good thing.
精彩评论