• 刨死你系列——手撕ArrayList


    不多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);
            }
        }
    }
        
  • 相关阅读:
    面向对象知识点2
    面向对象知识点1
    面向对象知识点
    常用模块
    模块与包
    迭代器相关知识
    jquery.jqprint-0.3.js打印功能 以及页眉页脚设置显示与否
    js和layerjs配合实现的拖拽表格列
    iframe中跳转页面的区别
    select3搜索下拉树
  • 原文地址:https://www.cnblogs.com/Young111/p/11488788.html
Copyright © 2020-2023  润新知