java String.isEmpty() 和 String.equals("") 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6828362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between String.isEmpty() and String.equals("")
提问by mastaH
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:
我创建了一个带有三个文本框的“颜色选择器”,用户可以在其中定义 rgb 值。
要检查输入的值是否正确(仅 0-255 之间的数字),我正在使用以下内容:
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 if there is any difference.
我要问的是:使用更好String.isEmpty()
吗?我从来没有找到令人满意的答案,我一直想知道是否有任何区别。
回答by Charles Goodwin
I think isEmpty()
is a bit more efficient. However a smart compiler may optimize the equals("")
call anyway. From the OpenJDK source:
我认为isEmpty()
效率更高一些。然而,智能编译器equals("")
无论如何都可以优化调用。从OpenJDK 源代码:
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 hereon whether to use str.isEmpty()
or "".equals(str)
is spot on:
还有这里关于是否使用str.isEmpty()
或"".equals(str)
现场的答案:
The main benefit of
"".equals(s)
is you don't needthe 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
的主要好处
"".equals(s)
是您不需要空检查(equals
将检查其参数并返回false
是否为空),您似乎并不关心。如果您不担心s
为空(或正在检查它),我肯定会使用s.isEmpty()
; 它准确地显示了您正在检查的内容,您关心是否s
为空,而不是它是否等于空字符串
回答by Bozho
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)
是的,使用String.isEmpty()
. 它更干净(语义上)(性能也稍微好一点,但这不会引起注意)如果实例可以为空,请使用 commons-langStringUtils.isEmpty(string)
回答by Joachim Sauer
Since isEmpty()
checks if the length of the String
is 0 and ""
is the onlyString
with length 0, each String
for which isEmpty()
returns true
would also return true
to .equals("")
. So technically, they do the same thing.
因为isEmpty()
检查的长度String
为0,并且""
是唯一的String
长度为0,每次String
针对isEmpty()
回报true
也将返回true
到.equals("")
。所以从技术上讲,他们做同样的事情。
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 notapply.
另一个区别是,如果您编写了"".equals(someString)
,那么它将是“ null
-safe”的。换句话说:如果someString
是null
,这个构造将简单地评估为false
而不是抛出一个NullPointerException
。但是,如果您有,someString.equals("")
那么这将不适用。
The most importantdifference is how it's read: isEmpty()
makes the intention veryclear: you want to treat empty strings differently. .equals("")
is ever so slightly lessclear ("if that string equals that other string, that happens to be empty").
在最重要的区别是它如何阅读:isEmpty()
让意图非常要区别对待空字符串:清晰。.equals("")
是有一点点不太清楚(“如果该字符串等于其他字符串,出现这种情况是空”)。
回答by pap
Typically, I like to use equals but in reverse, ie:
通常,我喜欢使用 equals 但反过来,即:
"".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).
但是,是的,isEmpty() 是一个更简单的操作,但我认为它并没有带来任何显着的性能贡献(除非您正在编写嵌入式实时内容)。
回答by ypnos
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.
从理论上讲,确实如此。对于isEmpty()
,只需要查看字符串的内部元数据(例如,它的长度)。为了进行比较,您会期望发生更多的案例差异。
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()
最适合该目的。
回答by Tomasz Nurkiewicz
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.
isEmpty()
更快,因为它只比较类中的length
整数字段,而与空字符串比较最多会比较引用(类似的速度),最坏的情况是 - 运行 0 次迭代的循环。String
0
But the biggest difference is readability - isEmpty()
is shorter and easier to grasp. BTW I wish there was an isBlank()
shorthand for .trim().isEmpty()
...
但最大的区别是可读性——isEmpty()
更短更容易掌握。顺便说一句,我希望有一个isBlank()
速记.trim().isEmpty()
...
回答by SJuan76
With myString.equals("")
, first the compiler creates an String object (it is equivalent to myString.equals(new String(""))
.
使用myString.equals("")
,首先编译器创建一个 String 对象(它等价于myString.equals(new String(""))
.
So, isEmpty() should be a better option (although equals("") is very popular).
所以,isEmpty() 应该是一个更好的选择(虽然 equals("") 非常流行)。
回答by Andrey
One more reason using myString.equals("")
or myString.length() == 0
is that String#isEmpty()
method was introduced in Java 1.6.
使用myString.equals("")
or 的另一个原因myString.length() == 0
是该String#isEmpty()
方法是在 Java 1.6 中引入的。
So arguments to do not use String#isEmpty()
can be compatibility reasons with previous versions of Java.
因此,不使用的参数String#isEmpty()
可能是与以前版本的 Java 兼容的原因。
回答by Arjan Tijms
It's partly a matter of history and legacy uses. isEmpty()
was only added in JDK 6:
这部分是历史和遗留用途的问题。isEmpty()
仅在 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.
在此之前,大家都比较""
看一个String是否为空。旧习惯很难改掉,所以很多人继续使用""
比较。
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.
当然,正如其他人已经提到的,如果您使用"".equals(someString)
它,那么它自动为空安全。许多人通过创建静态 isEmpty 方法将 isEmpty 的想法与空安全性相结合。
回答by Alexander Pogrebnyak
isEmpty
was only introduced in 1.6. Check Sincetag in javadoc.
isEmpty
仅在 1.6 中引入。检查javadoc 中的自标记。
Therefore, if you are compiling for 1.5 and lower equals("")
is your only choice.
因此,如果您正在编译 1.5 及更低版本,equals("")
则是您唯一的选择。
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 ).
但是,如果您不关心版本兼容性,我会使用isEmpty
. 正如 Bozho 指出的那样,它在语义上更清晰(而且速度更快)。