【发布时间】:2011-03-20 06:56:30
【问题描述】:
我通常与string == null 一起测试它,所以我并不真正关心 null 安全测试。我应该使用哪个?
String s = /* whatever */;
...
if (s == null || "".equals(s))
{
// handle some edge case here
}
或
if (s == null || s.isEmpty())
{
// handle some edge case here
}
关于那个注意事项 - isEmpty() 甚至除了 return this.equals(""); 或 return this.length() == 0; 之外还做其他事情吗?
【问题讨论】:
-
请记住,
isEmpty()仅适用于 Java 6+。 -
您可以创建一个辅助方法 Util.String.hasValue(String s) 来检查 null、空和空格来处理所有情况。
-
@ColinD 可能不是问题 - J2SE 5.0 前段时间结束了其服务生命周期。
-
要考虑的另一件事是 "".equals() 将 Object 作为参数,因此如果参数类型从 String 更改为其他类型,无论好坏,您都不会收到编译器错误。