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?
MutableBoolean() Constructs a new MutableBoolean with the default value of false. MutableBoolean(boolean value) Constructs a new MutableBoolean with the specified value.
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).
Boolean is immutable like Strings, you can change the value of it and allocate new mem allocation, but the first reference remains on the memory allocation who has the false value.
Variables that are assigned a boolean value are (probably always, and definitely in this case) mutable, yes. They're also not restricted to being assigned boolean values, as variables are not staticly typed. But the booleans True and False themselves are not mutable. They are singletons that cannot be modified.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With