什么时候应该null时使用布尔值? [英] When should null values of Boolean be used?
问题描述
Java的布尔
允许值真正
和假
而布尔允许真正
,假
和空
。我开始我的布尔
取值转换为布尔
秒。这可能会导致在测试中崩溃如
Java boolean
allows values of true
and false
while Boolean allows true
, false
, and null
. I have started to convert my boolean
s to Boolean
s. This can cause crashes in tests such as
Boolean set = null;
...
if (set) ...
,而测试
if (set != null && set) ...
似乎做作且容易出错。
seems contrived and error-prone.
当,如果有的话,是非常有用使用布尔
s的空值?如果从来没有,那么是什么被包装对象的主要优势是什么?
When, if ever, is it useful to use Boolean
s 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
推荐答案
使用布尔
,而不是布尔
每次您可以。这将避免许多 NullPointerException异常
和让你的code更强劲。
Use boolean
rather than Boolean
every time you can. This will avoid many NullPointerException
s and make your code more robust.
布尔
是有用的,例如:
- 来存储布尔集合中(列表,地图等)
- 要重新present一个可空布尔(可空布尔列进来的数据库,例如)。空值可能意味着我们不知道这是否是真的还是假的,在这种情况下。
- 每次方法需要一个对象作为参数,你需要传递一个布尔值。例如,使用反射或类似
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()
.
这篇关于什么时候应该null时使用布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!