gpt4 book ai didi

java - String.isEmpty() 和 String.equals (""之间的区别)

转载 作者:IT老高 更新时间:2023-10-28 20:48:42 32 4
gpt4 key购买 nike

我创建了一个“颜色选择器”,其中包含用户定义 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);
}
}
}

我要问的是:使用 String.isEmpty() 更好吗?我从来没有找到令人满意的答案,我一直想知道是否有任何区别。

最佳答案

我认为 isEmpty() 效率更高一些。然而,智能编译器可能会优化 equals("") 调用。来自 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 }

还有 answer here关于是否使用 str.isEmpty()"".equals(str) 是正确的:

The main benefit of "".equals(s) is you don't need the null check (equals will check its argument and return false if it's null), which you seem to not care about. If you're not worried about s being null (or are otherwise checking for it), I would definitely use s.isEmpty(); it shows exactly what you're checking, you care whether or not s is empty, not whether it equals the empty string

关于java - String.isEmpty() 和 String.equals (""之间的区别),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6828362/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com