自己实现ArrayList

ArrayList最重要的基本方法Api:

set(int idx, AnyType newVak)

向目标索引idx设置值 newVal

 public AnyType set(int idx, AnyType newVal) {
        if (idx < 0 || idx >= size()) {
            throw new ArrayIndexOutOfBoundsException();
        }
        AnyType old = theItems[idx];
        theItems[idx] = newVal;
        return old;
    }

get(int idx)

读取目标索引idx的值

   public AnyType get(int idx) {
        if (idx < 0 || idx >= size()) {
            throw new ArrayIndexOutOfBoundsException();
        }
        return theItems[idx];
    }

ensureCapacity(int newCapacity)

可以叫扩容为newCapacity方法.

    public void ensureCapacity(int newCapacity) {
        /*theSize 数组实际大小*/
        if (newCapacity < theSize) {
            return;
        }
        /*创建新的数组,然后复制老数组值入新数组*/
        AnyType[] old = theItems;
        theItems = (AnyType[]) new Object[newCapacity];
        for (int i = 0; i < size(); i++) {
            theItems[i] = old[i];
        }
    }

size()

返回list的大小

    public int size() {
        return theSize;
    }

add()

添加元素

 public boolean add(AnyType x) {
        add(size(), x);
        return true;
    }

    public void add(int idx, AnyType x) {
        /*当存值得数组大小和list大小相等时,把存值数组扩容为1倍*/
        if (theItems.length == size()) {
            ensureCapacity(2 * theItems.length);
        }
        /*如果是在数组中间插入,后面的元素要向高位移动*/
        for (int i = theSize; i > idx; i--) {
            theItems[i] = theItems[i - 1];
        }
        theItems[idx] = x;
        theSize++;

    }

remove(int idx)

删除指定位置的元素


    public AnyType remove(int idx) {
        AnyType removeItem = theItems[idx];
        /*如果删除的元素是不是尾,那就需要高位向前移动*/
        for (int i = idx; i < size() - 1; i++) {
            theItems[i] = theItems[i + 1];
        }
        theSize--;
        return removeItem;
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 首先看一下集合体系继承树 Collection接口 Collection是最基本的集合接口,一个Collectio...
    SnowDragonYY阅读 1,221评论 0 2
  • 一、对于ArrayList需要掌握的七点内容 ArrayList的创建:即构造器 往ArrayList中添加对象:...
    rochuan阅读 931评论 0 0
  • 自醒格言 一一刘长有 2018.5.24 布衣暖,菜根香, 心静体健康; ...
    依然如故_8a07阅读 244评论 0 0
  • 《非暴力沟通》第九章 爱自己 要点: 1、当我们的表现不完美时,我们可以通过体会忧伤和自我宽恕,来看清个人成长的方...
    夜的第七章4G阅读 190评论 0 0
  • 周一的吟诵后半程不太好,我在讲声意时说的过多现场还是有些乱,看来这种方式对于这种大课和一二年级年龄段的孩子们来说还...
    童心居士海阔天空阅读 294评论 0 0

友情链接更多精彩内容