java 数组插入元素

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;  
    }  
}  

  

posted @ 2015-05-19 23:15  狂奔的小狮子  阅读(663)  评论(0编辑  收藏  举报