I am in a situation where I want to use mutable versions of things like Integer. Do I have to use these classes (below) or does Java have something built in?
http://www.java2s.com/Code/Java/Data-Type/Amutableintwrapper.htm
A: The answer to your question is simple: once an Integer instance is created, you cannot change its value. The Integer String , Float , Double , Byte , Long , Short , Boolean , and Character classes are all examples of an immutable class.
It is because all primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean, and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old.
For example, In Java, String, Integer, Double are Immutable classes, while StringBuilder, Stack, and Java array are Mutable.
Simple put, a mutable object can be changed after it is created, and an immutable object can't. Objects of built-in types like (int, float, bool, str, tuple, unicode) are immutable. Objects of built-in types like (list, set, dict) are mutable.
You could always wrap the value in an array like int[] mutable = {1};
if including the code for a mutable wrapper class is too cumbersome.
Since JDK 1.5 java now has java.util.concurrent.atomic.AtomicInteger
This is a thread safe mutable integer, example of use:
final AtomicInteger value = new AtomicInteger(0);
then later on:
value.incrementAndGet();
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