Mutable boolean field in Java

前端 未结 9 2240
挽巷
挽巷 2020-12-09 07:32

I need a mutable boolean field in Java (I will return this field via get* method later and it should be possible to modify this field).

Boolean doesn\'t work because

9条回答
  •  一向
    一向 (楼主)
    2020-12-09 08:00

    Why not use the boolean primitive ?

    e.g.

    private boolean myFlag = false;
    
    public void setMyFlag(boolean flag) {
       myFlag = flag;
    }
    

    Note your getter method can return a Boolean if required, due to the magic of autoboxing. This allows easy interchangeability between using primitives and their object equivalents (e.g. boolean vs. Boolean, or int vs. Integer).

    So to address your edited responses re. the methods you have available,

    public Object getAttribute(String attributeName)
    

    can be implemented by returning an autoboxed boolean,.

提交回复
热议问题