java中值通报和引用通报一直饱受争议难以区分,下面我通过几个例子来区分一下什么时间是值通报,什么时间是引用通报
1:首先先说值通报:根基范例(int ,float ,long,byte,short ,double, char,boolean)作为参数通报时,是通报值的拷贝,无论你怎么改变这个拷贝,原值是不会改变的
package com.test.list;
public class Test1 {
public static void main(String[] args) {
int i = 10;
System.out.println("before change "+i);
change(i);
System.out.println("After Change "+i);
}
public static void change(int i ){
i=11;
}
}
输出为:10
2:个中String范例在在通报进程中也当成根基范例来处理惩罚
这是因为str = “ppp” 相当于 new String(“ppp”);
public class Test2 {
public static void main(String[] args) {
String str = "abc";
System.out.println("Before change "+str);
change(str);
System.out.println("After change " + str);
}
public static void change(String str){
str = "ppp";
}
}
输出为:abc
3:而引用通报进程相当于 把工具在内存中的地点拷贝了一份通报给了参数
public class Test3 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("abc");
System.out.println("Before change " + sb);
change(sb);
System.out.println("After change " + sb);
}
public static void change(StringBuffer str){
str.append("ppp");//把工具在内存中的地点拷贝了一份通报给了参数
}
}
查察本栏目
输出为:abcppp
再譬喻:
public class Test5 {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("abcd");
System.out.println("Before change "+list);
change(list);
System.out.println("After change "+list);
}
public static void change(List<String> list){
list.add("ppp");
}
}
输出为:abcdppp 如下图所示:
public class Test4 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("abc");
System.out.println("Before change " + sb);
change(sb);
System.out.println("After change " + sb);
}
public static void change(StringBuffer str){
str = new StringBuffer();//这里改变了引用 ,指向了别的一个地点,故输出照旧没有改变
str.append("ppp");
}
}
输出为:abc 因为从头指向了别的一个内存空间
