How do I pass an integer wrapper class to a method in Java?

Ex in Java:

class A {
    private Integer x = new Integer(0);

    public void setValue(Integer q) {
        q = 20;
    }

    public void callX() {
       setValue(x);        // this does not set x to be 20,which is what i need. Is there a way?
    }
}

Solution

You can't

Wrapper types are immutable, so they effectively simulate the behavior of the basic type: by executing q = 20, you make the parameter q point to the new intstance of an integer with a value of 20, but it does not change the original instance of the X reference in the calling method

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>