Change the value of the final variable Integer

The A final object cannot be modified, 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 final Integer and change its int value?

I ask because I call the 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 it.

I can declare my int inside another class and this will work. But I wonder if this is necessary.

+4
source share
4 answers

No: a Integer is immutable, such as String .

But you can create your own class to insert an integer and use it instead of 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; } } 
+12
source

You cannot, because it is unchanged in design.

You can set the value to int[] or Integer[] or AtomicInteger

+6
source

You cannot change the final value of an integer value after assignment. However, you can delay the appointment. That is: - you can assign the final integer only once. You can do this either during declaration or in the initialization block or in the constructor.

+3
source

You can transfer your Integer to another object that is final, and then "replace" the Integer inside this wrapper with another.

+2
source

Source: https://habr.com/ru/post/1438037/


All Articles