java 更改最终整数变量的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12750165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:03:44  来源:igfitidea点击:

Change the value of final Integer variable

javaclassintegerfinal

提问by Majid Laissi

A finalobject cannot be changed, but we can set its attributes:

一个final对象不能改变,但我们可以设置它的属性:

final MyClass object = new MyClass();
object.setAttr("something");              //<-- OK
object = someOtherObject;                 //<-- NOT OK

Is it possible to do the same with a final Integerand change its intvalue?

是否可以对 a 执行相同的操作final Integer并更改其int值?

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 myIntinside of it.

我需要设置myInt它内部的值。

I can declare my intinside another class, and that would work. But I wonder if this is necessary.

我可以int在另一个类中声明我的内部,这会起作用。但我想知道这是否有必要。

回答by Denys Séguret

No : an Integeris immutable, just like for example String.

不: anInteger是不可变的,就像 example 一样String

But you can design your own class to embed an integer and use it instead of an Integer :

但是您可以设计自己的类来嵌入整数并使用它代替 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;
    }
}

回答by Peter Lawrey

You can't because it immutable by design.

你不能,因为它在设计上是不可变的。

You can set the value of an int[]or Integer[]or AtomicInteger

您可以设置的值int[]Integer[]AtomicInteger

回答by Rohit Jain

You cannot change the value of finalinteger once assigned.. However, you can delay the assignment., i.e. : - You can only assign a finalinteger once.. You can do it either at the time of declaration, or in initializer block, or in constructor..

您不能更改final分配后的整数值.. 但是,您可以延迟分配。,即: - 您只能分配一次final整数.. 您可以在声明时,或在初始化程序块中,或在构造器..

回答by Stijn Geukens

You could wrap your Integer in another object that is final and then 'replace' the Integer inside that wrapper object by another.

您可以将 Integer 包装在另一个最终对象中,然后用另一个对象“替换”该包装对象中的 Integer。