zoukankan      html  css  js  c++  java
  • 刨死你系列——手撕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);
            }
        }
    }
        
  • 相关阅读:
    CAS实战の简介
    高效程序员的45个习惯の排除万难奋勇前进
    高效程序员的45个习惯の对事不对人
    高效程序员的45个习惯の欲速则不达
    高效程序员的45个习惯の正确做事
    Java中Runnable和Thread的区别
    Intellij IDEA 14的注册机(Java版)
    session token防表单重提
    maven下@override标签失效
    Oracle sql 优化の索引监控
  • 原文地址:https://www.cnblogs.com/Young111/p/11488788.html
Copyright © 2011-2022 走看看