什么时候应该使用布尔值的空值?

2022-01-19 00:00:00 boolean java

Java boolean 允许 truefalse 的值,而 Boolean 允许 truefalsenull.我已经开始将我的 booleans 转换为 Booleans.这可能会导致测试崩溃,例如

Java boolean allows values of true and false while Boolean allows true, false, and null. I have started to convert my booleans to Booleans. This can cause crashes in tests such as

Boolean set = null;
...
if (set) ...

测试时

if (set != null && set) ...

似乎做作并且容易出错.

seems contrived and error-prone.

什么时候(如果有的话)使用带有空值的 Boolean 有用吗?如果从来没有,那么包裹对象的主要优点是什么?

When, if ever, is it useful to use Booleans with null values? If never, then what are the main advantages of the wrapped object?

更新:有很多有价值的答案,我在自己的答案中总结了一些.我充其量只是 Java 的中级,所以我试图展示我认为有用的东西.请注意,问题是措辞不正确"(布尔值不能具有空值"),但我已经离开它以防其他人有同样的误解

UPDATE: There has been such a lot of valuable answers that I have summarised some of it in my own answer. I am at best an intermediate in Java so I have tried to show the things that I find useful. Note that the question is "incorrectly phrased" (Boolean cannot "have a null value") but I have left it in case others have the same misconception

推荐答案

尽可能使用 boolean 而不是 Boolean.这将避免许多 NullPointerException 并使您的代码更加健壮.

Use boolean rather than Boolean every time you can. This will avoid many NullPointerExceptions and make your code more robust.

Boolean 很有用,例如

  • 将布尔值存储在集合(列表、地图等)中
  • 表示一个可为空的布尔值(例如,来自数据库中的一个可为空的布尔值列).在这种情况下,null 值可能意味着我们不知道它是真还是假".
  • 每次方法需要一个对象作为参数时,您都需要传递一个布尔值.例如,当使用反射或 MessageFormat.format() 等方法时.
  • to store booleans in a collection (List, Map, etc.)
  • to represent a nullable boolean (coming from a nullable boolean column in a database, for example). The null value might mean "we don't know if it's true or false" in this context.
  • each time a method needs an Object as argument, and you need to pass a boolean value. For example, when using reflection or methods like MessageFormat.format().

相关文章