Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the value of final Integer variable

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 its int 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.

like image 808
Majid Laissi Avatar asked Nov 29 '22 08:11

Majid Laissi


1 Answers

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;
    }
}
like image 57
Denys Séguret Avatar answered Dec 04 '22 12:12

Denys Séguret