往数组的指定位置插入一个元素

/**
 * 用arraycopy()实现往数组指定位置插入一个指定的元素
 * @author HQ
 * @e-mail ahmashq95@gmail.com
 * @date 2018/10/8.
 */
public class test {
    public static void main(String[] args) {
        String s1[]={"aa","bb","cc","dd"};
 
        s1=insertElment(s1,3,"xx");
        for(String temp:s1){
            System.out.println(temp);
        }
 
    }
 
    /**
     * 返回已经插入后的数组
     * @param str
     * @param index
     * @param elment
     * @return
     */
    public  static String[] insertElment(String str[],int index,String elment){
        String s2[]=new String[str.length+1];
        System.arraycopy(str,0,s2,0,index);
        s2[index]=elment;
        System.arraycopy(str,index,s2,index+1,str.length-index);
        return s2;
    }
}

 

posted @ 2018-11-07 10:32  dreaming达摩  阅读(3125)  评论(0)    收藏  举报