首页 > 其他 > 详细

手撕ArrayList

时间:2019-09-09 00:34:48      阅读:93      评论:0      收藏:0      [点我收藏+]

不多BB,直接上代码:

public class MyArrayList {
    //创建数组对象
    private Object[] elements;
    //已使用数组长度
    private int size = 0;
    //初始化数组长度
    private final static int INIT_LENGTH = 10;
    //数组最大长度
    private int static int MAX_LENGTH = Integer.MAX_VALUE;

    //无参构造方法
    public MyArrayList() {
        this(INIT_LENGTH);
    }

    //有参构造方法
    public MyArrayList(int capacity) {
        if (capacity < 0) {
            System.out.println("创建集合失败");
        }
        elements = new Object[capacity];
    }

    //获取已使用数组长度
    public int size() {
        return size;
    }

    //判断数组是否为空
    public boolean isEmpty() {
        return size == 0;
    }

    //添加数组元素
    public void add(E e) {
        checkCapacity(size);
        elements[size++] = e;
    }

    //指定位置添加元素
    public void add(int index, E e) {
        checkRange(index);
        checkCapacity(size);
        System.arraycopy(elements, index, elements, index + 1, size - index);
        elements[index] = e;
        size++;
    }

    //查找指定元素
    public E get(int index) {
        checkRange(index);
        return elements[index];
    }

    //删除指定元素
    public E remove(int index) {
        checkRange(index);
        int moveSize = size - index - 1;
        E value = get(index);
        //判断是否为数组最后一个元素
        if (moveSize > 0) {
            System.arraycopy(elements, index + 1, elements, index, moveSize);
        }
        elements[size--] = null;
        return value;
    }

    //检查数组下标是否越界
    public void checkRange(int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("数组下标越界");
        }
    }

    //检查是否需要扩容
    public void checkCapacity(int size){
        if(size ==  elements.length){
            int newLength = size<<1 < MAX_LENGTH ? size<<1 : MAX_LENGTH;
            elements = Arrays.copyOf(elements, newLength);
        }
    }
}
    

 

手撕ArrayList

原文:https://www.cnblogs.com/Young111/p/11488788.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!