Java study notes (7)-array copy and expansion

Array copy

数组的复制可以有三种方法
1.暴力复制,即直接通过for循环来对数组进行复制,将本数组的值遍历传给新的数组
2.System.arraycopy(a,b,c,d,e)
	其中有五个参数
	a,原数组  b,从原数组哪里开始复制 c,新数组  d,新数组哪里开始传入  e,第二个数组传入的地方
3.Arrays.copyOf(a,b)
	a,表示原数组 b,表示将原数组的多少个元素复制过来

Array expansion

数组的扩容是指增加数组的容量,存放更多的元素
一般数组的扩容,思路就是创建新的容量更大的数组,将旧的数组复制给新的数组。
//利用System.arraycop方法进行复制
 public static int[] concat(int[] a, int[] b) {
    
    
  int[] c= new int[a.length+b.length];
     System.arraycopy(a, 0, c, 0, a.length);
     System.arraycopy(b, 0, c, a.length, b.length);
     return c;
    }
但是上述方法不常用于数组的扩容,一般采用的方法是Arrays.copyOf(a,b)方法
 public static int[] addsize1(int[] a) {
    
    
  a=Arrays.copyOf(a, a.length*2);
  return a;
 }

Guess you like

Origin blog.csdn.net/qq_42351519/article/details/110878106