优雅的方式来检查两个布尔值是否相等,但有一个特殊情况,即False == null?

huangapple go评论99阅读模式
英文:

Elegant way to check if two Booleans are equal, with a caveat where False==null?

问题

我目前只是将空值规范化为Boolean.FALSE,然后进行检查。但是否有一些工具可以干净地执行此操作?

重构为布尔值不是一个选项,因为这些变量来自外部对象参数,其中False等同于null。

示例:

  1. Boolean A = null;
  2. Boolean B = Boolean.FALSE;
  3. if(Objects.equals(A, B)){ //应返回true
  4. ...
  5. }
英文:

I'm currently just normalizing nulls to Boolean.FALSE, then doing the check. But is there some util that does this cleanly?

Refactoring to boolean is not an option as these variables come from an external object parameter, where False is equivalent to null.

Example:

  1. Boolean A = null;
  2. Boolean B = Boolean.FALSE;
  3. if(Objects.equals(A,B)){ //should return true
  4. ...
  5. }

答案1

得分: 2

Boolean.TRUE.equals(v) 如果 vTRUE,将会返回 true;如果 vFALSE 或者是 null,则返回 false。你可以利用这个来比较两个 Boolean 值(将 null 和 FALSE 视为相等),像这样:

  1. if (Boolean.TRUE.equals(a) == Boolean.TRUE.equals(b)) {
  2. ...
  3. }
英文:

Boolean.TRUE.equals(v) will evaluate to true if v is TRUE, and false if v is FALSE or null. Using that you can compare your two Boolean values (considering null and FALSE as equivalent) like this:

  1. if (Boolean.TRUE.equals(a)==Boolean.TRUE.equals(b)) {
  2. ...
  3. }

答案2

得分: 0

也许使用可选项会看起来不错?

  1. Optional.ofNullable(A).orElse(Boolean.FALSE).equals(B)
英文:

Maybe using optionals looks nice?

  1. Optional.ofNullable(A).orElse(Boolean.FALSE).equals(B)

huangapple
  • 本文由 发表于 2020年10月10日 00:45:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64284154.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定