Change the value of final Integer variable
Solution 1
No : an Integer
is immutable, just like for example String
.
But you can design your own class to embed an integer and use it instead of an Integer :
public class MutableInteger {
private int value;
public MutableInteger(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
Solution 2
You can't because it immutable by design.
You can set the value of an int[]
or Integer[]
or AtomicInteger
Solution 3
You cannot change the value of final
integer once assigned.. However, you can delay the assignment., i.e. : - You can only assign a final
integer once.. You can do it either at the time of declaration, or in initializer block, or in constructor..
Solution 4
You could wrap your Integer in another object that is final and then 'replace' the Integer inside that wrapper object by another.
![Majid Laissi](https://i.stack.imgur.com/TIl7w.png?s=256&g=1)
Majid Laissi
Updated on June 04, 2022Comments
-
Majid Laissi about 2 years
A
final
object cannot be changed, but we can set its attributes:final MyClass object = new MyClass(); object.setAttr("something"); //<-- OK object = someOtherObject; //<-- NOT OK
Is it possible to do the same with a
final Integer
and change itsint
value?I'm asking because I call a worker:
public SomeClass myFunction(final String val1, final Integer myInt) { session.doWork(new Work() { @Override public void execute(...) { //Use and change value of myInt here //Using it requires it to be declared final (same reference) } }
And i need to set the value of
myInt
inside of it.I can declare my
int
inside another class, and that would work. But I wonder if this is necessary. -
sheidaei over 11 yearsI would have used String instead of Number, since he has used it in his example :D too picky, I know :D but a great short answer
-
Benj over 10 yearsYou can simplify that by making
value
public. This is crappy but efficient. Then, you will accessmyMutableIntegerObj.value
(e.g. from an inner class). +1 for @dystroy