ArrayList的底层实现

ArrayList的底层实现,第1张

 学习数据结构时看了java集合中的ArrayList的实现,照着书上写了一遍,并添加了个人理解的注释

一起学习,卷啊~卷啊~

package Arraytest;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Consumer;

public class MyArraylist implements Iterable {
    private static final int DEFAULT_CAPACITY=10;  //默认数组长度
    private int theSize;   //数组当前的长度
    private AnyType[] theIntems;  //任何类型的数组 真实的ArrayList的实现是Object[]

    public MyArraylist(){
        doCrear();        //创建实例需要进行初始化 *** 作
    }
    public void clear(){   //清零
        doCrear();
    }
    public void doCrear(){  //做一个初始化的 *** 作
        theSize=0;
        ensureCapacity(DEFAULT_CAPACITY);
    }
    public  int size(){    //该方法的特点?
        return theSize;
    }
    public boolean isEmpty(){   //该方法是为了判断集合是否为空
        if (theSize>0){
            return false;
        }else {
            return true;
        }
    }
    public AnyType get(int index){  //通过index来获取值
        if (index<0||index>size())    //判断索引是否小于0或大于当前数组的最大值,抛出异常
            throw new ArrayIndexOutOfBoundsException();
        return theIntems[index];
    }
    public AnyType set(int index,AnyType m){  //替换原数组这种的某个元素,返回被替换的元素
        if (index<0||index>size())    //判断索引是否小于0或大于当前数组的最大值,抛出异常
            throw new ArrayIndexOutOfBoundsException();
        AnyType old=theIntems[index];
        theIntems[index]=m;
        return old;
    }
    //该方法用于从老数组当中的内容拷贝到新数组
    public void ensureCapacity(int newCapacity){
        if (newCapacityindex;i++)   //将index后面的元素向后推一位
            theIntems[i]=theIntems[i-1];
        theIntems[index]=x;    //将index的位置存放x

        theSize++;
    }
    public AnyType remove(int index){   //根据下标删除某个元素,返回删除的元素
        AnyType removeItem=theIntems[index];
        for (int i=index;i

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/741273.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)