Why does autoboxing in Java allow me to have 3 possible values for a boolean?

后端 未结 9 675
你的背包
你的背包 2020-12-06 07:43

Reference: http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html

\"If your program tries to autounbox null, it will throw a NullPointerEx

9条回答
  •  星月不相逢
    2020-12-06 07:48

    In addition to everything said here, there are cases where you would very much want to have a third value for booleans - the case of an "optional" property.

    We usually encounter it with databases, with boolean columns that allow nulls. Without using Booleans, we would need to use two separate variables, one indicating the value and another whether it is valid.

    In fact, if you look at the JDBC API, you can see an example of this problem, where columns get a default value if they are null (e.g., a 0 for numeric fields), and then you have to call "wasNull" to check whether it is a true 0 or a fake null!

提交回复
热议问题