Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutable boolean field in Java

Tags:

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?

like image 981
Oleg Vazhnev Avatar asked Sep 06 '09 11:09

Oleg Vazhnev


People also ask

What is mutable boolean in Java?

MutableBoolean() Constructs a new MutableBoolean with the default value of false. MutableBoolean(boolean value) Constructs a new MutableBoolean with the specified value.

How do you make a boolean mutable in Java?

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).

Is boolean immutable in Java?

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.

Are boolean variables mutable?

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.


1 Answers

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.

like image 152
Thomas Jung Avatar answered Sep 22 '22 09:09

Thomas Jung