Mutable boolean field in Java

前端 未结 9 2122
挽巷
挽巷 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 07:59

    What about just using the boolean primitive?

    private boolean value;
    
    public void setValue(boolean value) {
        this.value = value;
    }
    
    public boolean getValue() {
        return value;
    }
    
    0 讨论(0)
  • 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,.

    0 讨论(0)
  • 2020-12-09 08:01

    Maybe write yourself a wrapper class

    class BooleanHolder {
        public boolean value;
    }
    

    Or make a generic holder class (which means you will have to use class Boolean instead of primitive boolean):

    class Holder<T> {
        public T value;
    }
    

    You then return the wrapper class instead of the value itself, which allows the value inside the wrapper to be modified.

    0 讨论(0)
  • 2020-12-09 08:07

    The answer I liked most was from Adam to write your own wrapper class... OK

    /* Boolean to be passed as reference parameter */
    public class Bool {
    
         private boolean value;
    
         public Bool() {
             this.value = false;
         }
    
         public boolean is() {
             return this.value;
         }
    
         public void setTrue() {
             this.value = true;
         }
    
         public void setFalse() {
             this.value = false;
         }
     }
    
    0 讨论(0)
  • 2020-12-09 08:10

    You can use a boolean array

    final boolean[] values = { false };
    values[0] = true;
    
    0 讨论(0)
  • 2020-12-09 08:10

    If you are using Android, you can use the android.util.Mutable* objects which wrap various primitive values. For example, quoting from the SDK source:

    public final class MutableBoolean {
      public boolean value;
    
      public MutableBoolean(boolean value) {
          this.value = value;
      }
    }
    
    0 讨论(0)
提交回复
热议问题