我正在使用递归,并且我希望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
}但是在下面的代码中(我使用的是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++;
}
}那么为什么primitve包装类的行为不同呢?毕竟,两者都是对象,在reucrsive调用中,我传递的是Integer对象,而不仅仅是int,因此Integer对象也必须保持它的值。
发布于 2012-06-24 20:23:23
Java包装器类型是不可变的。他们的价值观永远不会改变。
counter++实际上是counter = counter + 1;即创建了一个新对象。
发布于 2012-06-24 20:23:37
一些对象,比如String,Integer etc....are是不变的,即使它们是对象...
试试这个链接......
http://www.javaranch.com/journal/2003/04/immutable.htm
我建议你这样做......
public void recursiveMethod(Integer counter)
{
if (counter == 10)
return counter; // return the value
else
{
counter++;
counter=recursiveMethod(counter);
}
}
public static void main(String[] args)
{
Integer c = new Integer(5);
c=(Integer)new TestSort().recursiveMethod(c);
System.out.println(c); // print 5
}我相信你在使用这两种方法时唯一的区别是
使用int就像使用任何其他语言一样使用java原语,而Integer包含wait(), notify(),parsing,hashcode等方法。
https://stackoverflow.com/questions/11177358
复制相似问题