When should null values of Boolean be used?

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

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

14条回答
  •  独厮守ぢ
    2020-12-04 07:39

    For all the good answers above, I'm just going to give a concrete example in Java servlet HttpSession class. Hope this example helps to clarify some question you may still have.

    If you need to store and retrieve values for a session, you use setAttribute(String, Object), and getAttribute(String, Object) method. So for a boolean value, you are forced to use the Boolean class if you want to store it in an http session.

    HttpSession sess = request.getSession(false);
    Boolean isAdmin = (Boolean) sess.getAttribute("admin");
    if (! isAdmin) ...
    

    The last line will cause a NullPointerException if the attribute values is not set. (which is the reason led me to this post). So the 3 logic state is here to stay, whether you prefer to use it or not.

提交回复
热议问题