java System.arraycopy()

package study.stage2;

import java.util.Arrays;

/**
* Created by Sandy.Liu on 2017/7/19.
*/
public class ArrayTest {
public static void main(String[] args) throws Exception{
int array[] = {3,4,2,24,6,-23,-4,-56};
System.out.println(array.length);//8
printArray(array);//{3,4,2,24,6,-23,-4,-56}
array = insertElement(array,1,5);
printArray(array);//{3,4,2,24,6,1,-23,-4,-56}
Arrays.sort(array);
printArray(array);//{-56,-23,-4,1,2,3,4,6,24}
int index = Arrays.binarySearch(array,4);
System.out.println(index);
}
public static void printArray(int array[]){
for(int i=0;i<array.length;i++){
System.out.print(array[i]+" ");
}
System.out.println();
}

public static int[] insertElement(int original[], int element, int index){
int length = original.length;
if(index<0){
System.out.println("out of range");
}
else if(index>original.length){
System.out.println("out of range");
}
int destination[] = new int[length+1];
//arrayCopy(originalArray,index, targetArray,index1,count) 把orginal里的从index位开始的值copy到targetArray里从index1开始的位置,
// ,copy的位数是count
System.arraycopy(original,0,destination,0,index);
destination[index]=element;
System.arraycopy(original,index,destination,index+1,length-index);
return destination;

}
}

posted on 2017-07-19 12:03  永恒自由森林  阅读(385)  评论(0编辑  收藏  举报

导航