天天看点

java怎么区分值传递和引用传递

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 因为重新指向了另外一个内存空间