英文:
Elegant way to check if two Booleans are equal, with a caveat where False==null?
问题
我目前只是将空值规范化为Boolean.FALSE,然后进行检查。但是否有一些工具可以干净地执行此操作?
重构为布尔值不是一个选项,因为这些变量来自外部对象参数,其中False等同于null。
示例:
Boolean A = null;
Boolean B = Boolean.FALSE;
if(Objects.equals(A, B)){ //应返回true
...
}
英文:
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:
Boolean A = null;
Boolean B = Boolean.FALSE;
if(Objects.equals(A,B)){ //should return true
...
}
答案1
得分: 2
Boolean.TRUE.equals(v)
如果 v
是 TRUE
,将会返回 true;如果 v
是 FALSE
或者是 null,则返回 false。你可以利用这个来比较两个 Boolean
值(将 null 和 FALSE
视为相等),像这样:
if (Boolean.TRUE.equals(a) == Boolean.TRUE.equals(b)) {
...
}
英文:
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:
if (Boolean.TRUE.equals(a)==Boolean.TRUE.equals(b)) {
...
}
答案2
得分: 0
也许使用可选项会看起来不错?
Optional.ofNullable(A).orElse(Boolean.FALSE).equals(B)
英文:
Maybe using optionals looks nice?
Optional.ofNullable(A).orElse(Boolean.FALSE).equals(B)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论