当我比较空字符串和空字符串

时间:2019-06-11 15:05:31

标签: java

我需要比较一个空字符串(“”)和一个空字符串,然后返回true。

String a = "";
String b = null;

// return TRUE if I compare "" and null
return TRUE if I compare null and null
return TRUE if I compare "" and ""

return false if a or b has some value

2 个答案:

答案 0 :(得分:1)

您可以使用一个函数来避免重复自己:

String a = ...;
String b = ...;

Predicate<String> isNullOrEmpty = s -> s == null || s.equals("");
return isNullOrEmpty.test(a) && isNullOrEmpty.test(b);

您还可以依赖提供StringUtils.isEmpty()的Apache Command Lang:

return StringUtils.isEmpty(a) && StringUtils.isEmpty(b);

答案 1 :(得分:-1)

您的实际用例不是将字符串相互比较,而是要检查两者中的一个是否不为空。

以下代码片段可以完成这项工作:

public boolean func(String a, String b) {
    if (a != null && !a.isEmpty()) {
        return false;
    }
    if (b != null && !b.isEmpty()) {
        return false;
    }
    return true;
}
相关问题