Does Java have mutable types for Integer, Float, Double, Long?
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
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();
No, Java doesn't have these built in. And that is for a reason. Using mutable types is dangerous, as they can easily be misused. Additionally, it is really easy to implement it. For example, commons-lang has a MutableInt
.
Here's a small class I made for a mutable integer:
public class MutableInteger {
private int value;
public MutableInteger(int value) {
this.value = value;
}
public void set(int value) {
this.value = value;
}
public int intValue() {
return value;
}
}
You could easily extend this to any other primitive. Of course, like everyone else is saying, you should use it carefully.
You can use an nnnn[] as a mutable object for any primitive type as @Alexandre suggests, java also has AtomicInteger and AtomicLong.
IMHO int is usually a better choice than Integer and that is mutable.
Can you more details of why you need a mutliple object, perhaps there is another way to achieve the same thing.