,一个Integer对象在堆中被创建,添加到了现有的list对象。所以原始的list引用可以看见这次修改,因为2个引用都指向了内存中的同一个对象
自定义对象
public static void main(String[] args) {
Student student = new Student();
System.out.println("Value of name before Student modification = " + student.getName());
modifyStudent(student);
System.out.println("Value of name after Student modification = " + student.getName());
}
private static void modifyStudent(Student student)
{
student.setName("Alex");
}
输出:
Value of name before Student modification = null
Value of name after Student modification = Alex
说明:
student对象在堆中被创建,在堆栈中存储着指向它的引用。当调用calling modifyStudent(),在堆栈中创建了这个引用的拷贝,传递到了方法中。所以任何对这个对象属性的修改会影响原始的对象引用
结论
在Java中,参数都是按值传递的。被传递到方法中的拷贝值,要不就是一个引用或一个变量,取决于原始参数的类型。从现在开始,下面的几条规则将帮助你理解方法中对于参数的修改怎么影响原始参数变量。
- 在方法中,修改一个基础类型的参数永远不会影响原始参数值。
- 在方法中,改变一个对象参数的引用永远不会影响到原始引用。然而,它会在堆中创建了一个全新的对象。(译者注:指的是包装类和immutable对象)
- 在方法中,修改一个对象的属性会影响原始对象参数。
- 在方法中,修改集合和Maps会影响原始集合参数。