利用java.lang.System中的arraycopy()方法实现往数值指定中的指定位置插入一个指定元素

版权声明:未经博主同意不得转载 https://blog.csdn.net/huang_qiang123/article/details/82970055

实际开发中,我们往往需要往一个数组的指定位置插入一个指定元素;

/**
 * 用arraycopy()实现往数组指定位置插入一个指定的元素
 * @author HQ
 * @e-mail [email protected]
 * @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;
    }
}

猜你喜欢

转载自blog.csdn.net/huang_qiang123/article/details/82970055