我正在使用递归,我希望一个Integer对象在递归调用中保留其值.例如
public void recursiveMethod(Integer counter) {
if (counter == 10)
return;
else {
counter++;
recursiveMethod(counter);
}
}
public static void main(String[] args) {
Integer c = new Integer(5);
new TestSort().recursiveMethod(c);
System.out.println(c); // print 5
}
Run Code Online (Sandbox Code Playgroud)
但是在下面的代码中(我使用的是Counter类而不是Integer包装类,值保持不变)
public static void main(String[] args) {
Counter c = new Counter(5);
new TestSort().recursiveMethod(c);
System.out.println(c.getCount()); // print 10
}
public void recursiveMethod(Counter counter) {
if (counter.getCount() == 10)
return;
else {
counter.increaseByOne();
recursiveMethod(counter);
}
}
class Counter {
int count = 0;
public Counter(int count) {
this.count = count;
}
public int getCount() {
return this.count;
}
public void increaseByOne() {
count++;
}
}
Run Code Online (Sandbox Code Playgroud)
那么为什么primitve包装类表现不同.毕竟,两者都是对象,在reucrsive调用中,我传递的是Integer对象而不仅仅是int为了使Integer对象也必须保持其值.