Question

Mutable boolean field in Java

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 there are no set* methods in the Boolean class (I would say that Boolean is immutable, you can only change the reference, but you can't change the object itself).

I guess I can use Boolean array of size 1. But probably there are more elegant solutions?

Why doesn't Java have such a simple thing?

 45  44096  45
1 Jan 1970

Solution

 66

Immutable classes are easier to work with. They'll never change and there will be no problems with concurrent code. (Basically, there are fewer possibilities to break them.)

If you would like to return a reference to your Boolean value, you can use java.util.concurrent.atomic.AtomicBoolean if you're working with multiple threads or plain old org.apache.commons.lang.mutable.MutableBoolean.

2009-09-06

Solution

 29

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.

2009-09-06