印象中记得 java 的参数传递方式是引用传递,但是为什么对于基本类型在函数里的参数修改不会影响到函数外传入的变量呢,是因为对于基本类型来说,值就存储在变量本身了吗,还是说基本类型的值是存在栈上,只不过随着函数调用,参数压栈后,对应的值也会跟着参数复制一份,对参数本身的修改就不会影响到函数外传入的值,而对象参数是指向堆的一个地址,即使复制了,也是同一个地址,因此在函数内修改参数对象的值会影响函数外传入的对象值。
如果想要让 java 也能做到类似 C 语言的解引用,类似 int* aAddr = &b,是不是只要让栈地址暴露出去就可以了。
public class Reference {
public static void main(String[] args) {
Reference reference = new Reference();
Student student = new Student(1);
System.out.printf("before change student's age: %d\n", student.age);
reference.changeReference(student);
System.out.printf("after change student's age: %d\n", student.age);
int a = 1;
System.out.printf("before change int: %d\n", a);
reference.changePrimitive(a);
System.out.printf("after change int: %d\n", a);
}
void changeReference(Student s) {
s.age += 1;
}
void changePrimitive(int a) {
a = 2;
}
static class Student {
int age;
public Student(int age) {
this.age = age;
}
}
}