为什么写这个呢因为以前对都是对基本类型进行操作的时候后,返回的值并不会改变,但如果是数组的话就会改变。
以下这段加了下滑线的话是引用https://www.cnblogs.com/PopShow/p/5207974.html这个博客的
在java中,不允许程序员选择值传递还是地址传递各个参数,基本类型总是按值传递。对于对象来说,是将对象的引用也就是副本传递给了方法,在方法中只有对对象进行修改才能影响该对象的值,操作对象的引用时是无法影响对象。
现在说说数组:如果将单个基本类型数组的元素传递给方法,并在方法中对 其进行修改,则在被调用方法结束执行时,该元素中存储的并不是修改后的值,因为这种元素是按值传递,如果传递的是数组的引用,则对数组元素的后续修改可以 在原始数组中反映出来(因为数组本身就是个对象,int[] a = new int[2];,这里面的int是数组元素的类型,而数组元素的修改是操作对象)。
直接看测试代码:
package transit;
import java.util.ArrayList;
import java.util.List;
public class test {
public static void main(String args[]){
/* byte [] requestContent={0x01,0x02,0x03};
byte [] newRequestContent=new byte[3];
System.arraycopy(requestContent,0,newRequestContent,0,3);
requestContentDetail(newRequestContent);
System.out.print(requestContent[1]);*/
int []a={1,2,3};
byte []b={0x01,0x02,0x03};
int c=10;
String str =new String("helloWorld");
List list=new ArrayList();
list.add(1);
list.add(2);
System.out.println("进入函数前:");
System.out.println("整型数组:"+a[0]+"字节型数组:"+b[0]+"整型:" + c);
System.out.println("字符串:"+str+"数组大小:"+list.size());
math(a,b,c,str,list);
System.out.println("进入函数后:");
System.out.println("整型数组:"+a[0]+" 字节型数组:"+b[0]+" 整型:" + c);
System.out.println("字符串:"+str+" 数组大小:"+list.size());
}
public static void math(int []a,byte[] b,int c,String str,List list){
a[0]=100;
b[0]=0x09;
c++;
++c;
str="tonight eat chicken";
list.add(3);
System.out.println();
System.out.println("进入函数时:");
System.out.println("整型数组:"+a[0]+"字节型数组:"+b[0]+"整型:" + c);
System.out.println("字符串:"+str+"数组大小:"+list.size());
System.out.println();
}
}
点击执行后运行输出的值就可以很直观的看到具体是怎么回事了
=========================================分割线==================================================
关于java中的po对象也有这样子的问题需要使用jdk自带的BeanUtils.copyProperties方法复制对象
直接上代码,代码中的对象为任意对象。
public static void main(String[] args) {
try {
T t1 =new T();
T t2 =new T();
t1.setObject("1");
BeanUtils.copyProperties(t2,t1);
t2.setObject("2");
System.out.println(t1.getObject()+" "+t2.getObject());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
控制台打印出来的话就会是1 2,而不是2,2(如果两个对象直接用等号赋值)