Is Java 8 missing an OptionalBoolean?

前端 未结 4 1627
醉话见心
醉话见心 2020-12-29 20:23

As a primitive version of Optional*, Java 1.8 provides OptionalInt, OptionalLong and OptionalDouble.

But I cannot find the equivalent OptionalBoolean cl

4条回答
  •  生来不讨喜
    2020-12-29 20:55

    Apart for the desire to reduce the magnitude of the combinatorial explosion of primitive type specialisation classes I suspect one major reason for the absence of an OptionalBoolean is that the advantage of such a class is much smaller than the advantage of specialisations for the numeric types.

    The reason for why the advantage is smaller is that there are only two different values of the type boolean. Because of this, most of the time you only get two object of type Boolean. Those two are cached as Boolean.TRUE and Boolean.FALSE and reused in most cases, e.g. when booleans are auto-boxed. Numeric wrapper types have a number of cached objects for a small range of values, for other values a new object has to be allocated every time a primitive value is stored in a generic container such as Optional.

    So an Optional object is almost as efficient as an OptionalBoolean would be since no new Boolean have to be allocated to put an unboxed boolean into it.

    I could also be useful to have two cashed Optional available somewhere in the standard library, as Optional.TRUE/FALSE perhaps. I don't know the reason for why there isn't.

提交回复
热议问题