java中数组复制的两种方式

在java中数组复制有两种方式:

一:System.arraycopy(原数组,开始copy的下标,存放copy内容的数组,开始存放的下标,需要copy的长度);

  这个方法需要先创建一个空的存放copy内容的数组,再将原先数组得我内容复制到新数组中。

  

int[] arr = {1,2,3,4,5};  
   
int[] copied = new int[10];  
System.arraycopy(arr, 0, copied, 1, 5);//5 is the length to copy  
   
System.out.println(Arrays.toString(copied));  

 

二:Arrays.copyOf(原数组,copy后的数组长度);

  可用于扩容和缩容,不需要先创建一个数组,但实际上也是又创建了一个新得我数组,底层是调用了System.arraycopy()的方法;

  

int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new array  
System.out.println(Arrays.toString(copied));  
   
copied = Arrays.copyOf(arr, 3);  
System.out.println(Arrays.toString(copied));  

  

posted @ 2018-02-23 18:00  兰溪三日桃花雨  阅读(337)  评论(0编辑  收藏  举报