【问题标题】:I want to have a function that returns true, when I compare a null String and an Empty String [duplicate]当我比较空字符串和空字符串时,我想要一个返回 true 的函数 [重复]
【发布时间】:2019-06-11 15:05:31
【问题描述】:

我需要比较一个空(“”)字符串和一个空字符串并返回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

【问题讨论】:

  • 这很容易做到,你到底在坚持什么?
  • "" 相比 "" 不应该也返回 true 吗? nullnull 也是如此。您的要求不清楚。
  • @JonK 我试过 .equals 和 ==,在任何情况下都没有实现。
  • 请贴出无效的代码。
  • @davidxxx "" 与 "" 相比应为真,null 与 null 相比应为真,"" 与 null 相比也应为真

标签: java


【解决方案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);

【讨论】:

  • 如果 a 或 b 有一些价值呢?
  • 它返回假。你可以写一个单元测试,你可以检查所有这些
【解决方案2】:

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

下面的 sn-p 应该可以完成这项工作:

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

【讨论】:

    猜你喜欢
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    相关资源
    最近更新 更多