When should null values of Boolean be used?

前端 未结 14 2361
心在旅途
心在旅途 2020-12-04 07:32

Java boolean allows values of true and false while Boolean allows true, false, and null. I have

14条回答
  •  -上瘾入骨i
    2020-12-04 07:56

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

    Boolean is useful, for example

    • 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().

提交回复
热议问题