Java值传递和引用传递详解
当一个对象被当作参数传递到一个方法后,此方法可改变这个对象的属性,并可返回变化后的结果,那么这里到底是值传递还是引用传递? Java参数,不管是原始类型还是引用类型,传递的都是副本(有另外一种说法是传值,但是说传副本更好理解吧,传值通常是相对传址而言)。 如果参数类型是原始类型,那么传过来的就是这个参数的一个副本,也就是这个原始参数的值,这个跟之前所谈的传值是一样的。如果在函数中改变了副本的值不会改变原始的值。 如果参数类型是引用类型,那么传过来的就是这个引用参数的副本,这个副本存放的是参数的地址。如果在函数中没有改变这个副本的地址,而是改变了地址中的 值,那么在函数内的改变会影响到传入的参数。如果在函数中改变了副本的地址,如new一个,那么副本就指向了一个新的地址,此时传入的参数还是指向原来的 地址,所以不会改变参数的值。 例: public class ParamTest { public static void main(String[] args){ /** * Test 1: Methods can't modify numeric parameters */ System.out.println("Testing tripleValue:"); double percent = 10; System.out.println("Before: percent=" + percent); tripleValue(percent); System.out.println("After: percent=" + percent); /** * Test 2: Methods can change the state of object parameters */ System.out.println("nTesting tripleSalary:"); Employee harry = new Employee("Harry",50000); System.out.println("Before: salary=" + harry.getSalary()); tripleSalary(harry); System.out.println("After: salary=" + harry.getSalary()); /** * Test 3: Methods can't attach new objects to object parameters */ System.out.println("nTesting swap:"); Employee a = new Employee("Alice",70000); Employee b = new Employee("Bob",60000); System.out.println("Before: a=" + a.getName()); System.out.println("Before: b=" + b.getName()); swap(a,b); System.out.println("After: a=" + a.getName()); System.out.println("After: b=" + b.getName()); } private static void swap(Employee x,Employee y) { Employee temp = x; x=y; y=temp; System.out.println("End of method: x=" + x.getName()); System.out.println("End of method: y=" + y.getName()); } private static void tripleSalary(Employee x) { x.raiseSalary(200); System.out.println("End of method: salary=" + x.getSalary()); } private static void tripleValue(double x) { x=3*x; System.out.println("End of Method X= "+x); } } 显示结果: Testing tripleValue: Before: percent=10.0 End of Method X= 30.0 After: percent=10.0 Testing tripleSalary: Before: salary=50000.0 End of method: salary=150000.0 After: salary=150000.0 Testing swap: Before: a=Alice Before: b=Bob End of method: x=Bob //可见引用的副本进行了交换 End of method: y=Alice After: a=Alice //引用本身没有交换 After: b=Bob 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- 类型javax.servlet.ServletContext和javax.servlet.Servlet
- spring security国际化及UserCache的配置和使用
- 如何将windows-1250 / Cp1250中编码的String转换为utf-8?
- java中的正则表达式与indexOf的性能相比
- java – TestNG – @AfterMethod的优先级
- springboot实现拦截器之验证登录示例
- java – 为什么有些类在创建实例时不需要“New”这个词?
- java实现构造无限层级树形菜单
- SpringBoot使用Editor.md构建Markdown富文本编辑器示例
- java – 如何将写入的数据附加到文件?