第三章:数组[5常见算法]--[4复制]

①自定义逻辑

int[] array1 = new int[]{1,2,3,4};

int[] array2 = new int[array1.length];

for(int i = 0;i < array2.length;i++){

    array2[i] = array1[i];

}

System.arraycopy()--区间[a,b]

 

/*

* @param      src      the source array.//源数组

* @param      srcPos   starting position in the source array.//复制源数组的起始位置

* @param      dest     the destination array.//目标数组

* @param      destPos  starting position in the destination data.//目标数组开始位置

* @param      length   the number of array elements to be copied.//目标数组结束位置

*/

//public static native void arraycopy(Object src,  int  srcPos, Object dest, int destPos,  int length);

String[] A = {"H","e","l","l","o"};

String[] B = new String[3];

System.arraycopy(A, 0, B, 1, B.length - 1); // [a,b]

for(int i = 0; i < B.length; i ++){

  System.out.print(B[i] + " ");

}

//null H e

 

③Arrays.copyOf()

String[] a = {"a","d","e","w","f"};

String[] b = new String[4];

String[] c = new String[5];

b = Arrays.copyOf(a, b.length);

c = Arrays.copyOf(a, c.length);

System.out.println("b数组的元素:" + Arrays.asList(b));//b数组的元素:[a, d, e, w]

System.out.println("c数组的元素:" + Arrays.asList(c));//c数组的元素:[a, d, e, w, f]

④Arrays.copyOfRange()--区间[a,b) 

String[] a = {"a","d","e","w","f"};

String[] b = new String[4];

b = Arrays.copyOfRange(a, 2, 4);// [a,b)

System.out.println("b数组的元素:" + Arrays.asList(b));//b数组的元素:[e, w];

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

猜你喜欢

转载自www.cnblogs.com/Lucky-stars/p/11010122.html