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

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

/**
 * 用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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值