经常会碰到数组的操作,今天是关于数组的插入
import java.util.Arrays;
public class AddArray {
public static void main(String[] args) {
int[] arr = {1,4,2,4,11,33,22,67,43};
for (int i : sort(arr,23)) {
System.out.print(i+"\t");
}
System.out.println();
for (int i : sort1(arr,45)) {
System.out.print(i+"\t");
}
}
//使用 Arrays.copyOf
public static int[] sort(int[] arr,int num){
int[]copyArr = Arrays.copyOf(arr,arr.length+1);
copyArr[arr.length]=num;
Arrays.sort(copyArr);
return copyArr;
}
//使用 System.arraycopy
public static int[] sort1(int[] arr,int num){
int[]copyArr = new int[arr.length+1];
System.arraycopy(arr,0,copyArr,0,arr.length);
copyArr[arr.length]=num;
Arrays.sort(copyArr);
return copyArr;
}
}