Does Java have mutable types for Integer, Float, Double, Long?
Solution 1
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
.
Solution 2
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.
Solution 3
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();
Solution 4
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.
Solution 5
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.
Comments
-
smuggledPancakes over 4 years
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
-
Vishy about 12 years
int
is always mutable unless its alsofinal
-
mjaggard about 12 yearsIt's not really valid to say that a primitive type is mutable. It can be changed but so can every non-final object if you just point to a new object. For example
Integer a = 4;
thena = 5;
is valid code, butInteger
is not mutable. -
Vishy about 12 yearsI agree that
Integer
instances are not mutable even if references to them are, but that's a different type. -
msanjay about 12 yearsIsn't this a good way to have a reference int parameter? For example a function that returns a paginated List of items (from the database), but also the total number of records. In such a case, AtomicInteger or MutableInteger seem to be useful. Of course the other way would be to have a getTotalRecords property instead of returning it in the same method.
-
rogerdpack about 11 yearsMy guess is the java dev's wanted Integer to 'behave' like an int, which is..once you have a reference to it, it never changes (avoid confusion). But..it still seems odd to not have a mutable option somehow, to me...
-
GKFX over 9 years"Using mutable types is dangerous because they can easily be misused." Most things can be misused. Immutable types exist for cases where safety is important, although they can be changed by reflection. With those cases out of the way, there's no reason to prevent people from using mutable types when they need them.
-
Vlasec over 9 yearsA better way to put it, immutable types create less confusion in e.g. maps and sets. If you had a mutable Integer and changed its value where it served as a key, it would mess up the collection. However, in case you need some mutable implementation of Integer, nothing is easier than creating some class with an int value inside. And you can be creative there - make it e.g. a Counter or Countdown, not just a plain int that enables quite anything. Give it some logic (unless you develop in Java EE that works bottoms-up).
-
Snicolas almost 9 yearsIMHO the best option has it doesn't give false clues about concurrency as using an atomic interger does. And an array, really I would never do such a bad thing in my code.. ;)
-
Agoston Horvath over 7 yearsWhile very smart way to fix the problem, with Java9 coming up, you probably don't want to use this -- that would import the whole CORBA module just for an int holder.
-
Qw3ry over 7 yearsCould be a good idea to provide a single generic wrapper class instead so You don't end up with a
MutableInteger
,MutableDouble
,MutableString
etc. but instead have aMutable<Integer>
,Mutable<Double>
, ... The memory overhead (of usingInteger
overint
will usually not fall into account. But you get a single, ready to use class that can handle most cases (If you want your integer to be comparable or similar things you still need to subclass, though). -
Stijn de Witt almost 7 yearsIt might be a good idea to make it extend Number.
-
The Fluffy Robot over 6 yearsCertainly an old question, but hopefully someone can answer HOW they can be misused. What is so dangerous about using them?
-
GregT over 6 years@user1175807 As Vlasec had commented, if you accidentaly modify a variable you have used somewhere else, it will cause weird bugs. Even worse, let's say you're writing a program that works together with a client's code. You need to implement a method which has a parameter of mutable Integer type. Now if you modify the mutable Integer for any reason, then it would also be changed in the client's program, which is totally unexpected, and will cause bugs that are hard to find.
-
CompEng88 over 6 yearsthis is super clever and takes almost no space. plus avoids the syching done with AtomicInt.
-
Minas Mina almost 6 yearsThis thead safety comes at a performance cost, which in many cases is not needed. For example, a common use case for me is to increment a counter captured by a lambda. Using an atomic is overkill.
-
Tobias Liefke over 5 yearsYou should really think about your wording: Even if you use a lambda, your example is not functional, as that prohibits side effects. If you really write it functional, you don't need mutables:
someStreamGenerator().mapToDouble(Data::getValue).sum()
. Even for cumulating three different informations, there is a functional way by usingStream.reduce
orStream.collect
. I see no reason to refactor every loop to a functional code fragment, but if you want to go that way, you should go it until the end. -
Dirk Hillbrecht over 5 yearsAs I wrote: This is not proper style and for each and any new code this should not be used. But when refactoring 400.000+ lines of code which evolved within 15+ years, you find constructs where proper rewrite into truly functional constructs can be extremely difficult. Then, rewriting into such hybrid-style can be a sensible trade-off as you get at least the basic structure aligned.
for
andforeach
can be parts of complex frameworks which are functionally rewritten, so you have to align the rest of the code somehow around them. -
Tobias Liefke over 5 yearsYou are confusing lambdas and functional programming. In your example you didn't rewrite it "functional". And what is the point in rewriting everything with lambdas, when you lose readability, but don't get the advantages of functional programming? Why should one even try to get rid of every loop in a complex framework by using such hybrids?
-
Dirk Hillbrecht over 5 yearsYou have 1000 places with a certain idiom in your code. The idiom is driven by a library or whatever global structure. You replace that global structure with a new one based on functional approach and lambdas. 998 of your 1000 places can be converted cleanly into functional style. The remaining 2 are extremely difficult to convert properly. In such cases, I always mandate for converting into new style with such hybrid constructs. Only then you can get rid of whatever old global structures have been in the code. While not being perfect, the overall code quality increases.
-
Adam Burley about 4 years
int
is not mutable because if you pass it to a method, there is no way for the method to change its value and have the new value reflected in the calling method -
Vishy about 4 years@AdamBurley while you cannot pass by reference any local variable this is not what is meant by mutuality.