数组指定位置插入数据--JAVA

 《漫画算法--小灰的算法之旅》

每天学习一点数据结构,既是小灰的算法之旅,也是本人的算法之旅。

当前代码实现的是数组的指定位置插入数据的代码。

package com.java.array;

/**
 * 向数组插入数据的思想
 * 1、需要判断插入位置的下标是否是数组的正常范围之内
 * 2、如果数组实际元素达到数组容量的上限,则对数组进行扩容
 * 3、从右向左循环,将元素逐个向右移动,腾出的位置插入新的元素
 *
 * 当前程序:不允许随意插入任意位置的数据,不然报错。
 */
public class ArrayInsert {
    private int[] arr;
    private int size;

    public ArrayInsert(int capacity) {
        this.arr = new int[capacity];
        this.size = 0;
    }

    public static void main(String[] args) throws Exception {
        ArrayInsert aInsert = new ArrayInsert(4);
        aInsert.insert(0, 3);
        aInsert.insert(1, 9);
        aInsert.insert(2, 5);
        aInsert.insert(3, 7);
        aInsert.insert(2, 6);
        aInsert.insert(1, 8);
        aInsert.outArr();
    }

    /**
     * @param index   插入的下标
     * @param element 插入的元素
     * @throws Exception
     */
    private void insert(int index, int element) throws Exception {
        if (index < 0 || index > size) {
            throw new Exception("Out of Index");
        }
        if (size >= arr.length) {
            resize();
        }
        for (int i = size - 1; i >= index; i--) {
            arr[i + 1] = arr[i];
        }
        arr[index] = element;
        size++;
    }

    public void resize() {
        int[] newArr = new int[arr.length * 2];
        System.arraycopy(arr, 0, newArr, 0, arr.length);
        arr = newArr;
    }

    private void outArr() {
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

System.arraycopy()源码:

 * @param      src      the source array.
 * @param      srcPos   starting position in the source array.
 * @param      dest     the destination array.
 * @param      destPos  starting position in the destination data.
 * @param      length   the number of array elements to be copied.
 * @exception  IndexOutOfBoundsException  if copying would cause
 *               access of data outside array bounds.
 * @exception  ArrayStoreException  if an element in the <code>src</code>
 *               array could not be stored into the <code>dest</code> array
 *               because of a type mismatch.
 * @exception  NullPointerException if either <code>src</code> or
 *               <code>dest</code> is <code>null</code>.
 */
public static native void arraycopy(Object src,  int  srcPos,Object dest, int destPos,int length);

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值