package myintergertest;
/**
*
* @author Engineering
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//this one does not increment
Integer n = new Integer(0);
System.out.println("n=" + n);
Increment(n);
System.out.println("n=" + n);
Increment(n);
System.out.println("n=" + n);
Increment(n);
System.out.println("n=" + n);
Increment(n);
//this one will increment
MyIntegerObj myInt = new MyIntegerObj(1);
Increment(myInt);
System.out.println("myint = " + myInt.get());
Increment(myInt);
System.out.println("myint = " + myInt.get());
Increment(myInt);
System.out.println("myint = " + myInt.get());
}
public static void Increment(Integer n) {
//NO. this doesn't work because a new reference is being assigned
//and references are passed by value in java
n++;
}
public static void Increment(MyIntegerObj n) {
//this works because we're still operating on the same object
//no new reference was assigned to n here.
n.plusplus(); //I didn't know how to implement a ++ operator...
}
}
所有这些的结果是n = 0。整数n是一个对象,因此通过引用传递,所以为什么增量反映在调用方法(main)中?我预计输出为n = 0 n = 1 n = 2等…
更新:
注意我更新了上面的代码示例。如果我正确理解,Jon Skeet回答了为什么我的Int会增加,为什么没有n的问题。这是因为n在Increment方法中得到了一个新的引用。但是,由于MyInt调用了一个成员函数,所以我没有得到新的引用。
听起来我听得懂吗?