How to pass Integer wrapper class to a method in java?
Ex in java:开发者_如何学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?
}
}
You cannot.
Wrapper types are immutable, therefore they effectively emulate behaviour of primitive types: by executing q = 20
you make parameter q
point to the new intstance of Integer
with value 20
, but it doesn't change the original instance referenced by x
in the calling method.
You could use AtomicInteger
instead, it's mutable:
private AtomicInteger x = new AtomicInteger(0);
public void setValue(AtomicInteger q) {
q.set(20);
}
public void callX() {
setValue(x);
}
In Java this behaviour would be considered very confusing. generally a setter, like setValue takes a value and does not alter its arguments. A getter typically is used to return a value.
BTW: IMHO Don't use wrappers unless you have a good reason to do so.
Instead you might do something like this.
class A {
public int getValue() {
return 20;
}
public void callX() {
int x = getValue(); // this sets x to be 20.
}
}
精彩评论