Java 基础 - ArrayList 源码

本贴最后更新于 1562 天前,其中的信息可能已经水流花落

最近发现有些源码直接翻译英文注释就可以了,论学好英语的重要性,之后的源码就以翻译注释为主了

继承

image.png
这些个接口或类基本都认识,不多介绍,主要介绍 RandomAccess 接口;
RandomAccess 接口也是一个空接口,作用可以看接口的注释:

Marker interface used by List implementations to indicate that they support fast (generally constant time) random access. The primary purpose of this interface is to allow generic algorithms to alter their behavior to provide good performance when applied to either random or sequential access lists.
这段话翻译的意思是:

List 实现使用的标记接口,指示它们支持快速(通常是恒定时间)随机访问。此接口的主要目的是允许通用算法在应用于随机或顺序访问列表时更改其行为以提供良好的性能。
很容易想到 ArrayList 是数组实现,可以通过下标轻松实现随机访问,添加这个标记接口就是为了区分 LinkedList,在循环时,ArrayList 使用 for 循环,而 LinkedList 使用迭代器。

变量

// 默认容量为10
private static final int DEFAULT_CAPACITY = 10;
//构造方法中容量为0或传入空集合时的空实例
private static final Object[] EMPTY_ELEMENTDATA = {};
//用户使用默认容量且没有添加一个元素的时候的空示例
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
// 元素数组
transient Object[] elementData;
//列表长度
private int size;
//最大容量
 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//  从结构上修改此列表的次数。结构修改是那些改变列表大小的修改,或者以其他方式干扰列表,使得正在进行的迭代可能产生不正确的结果。
protected transient int modCount = 0;

核心函数

扩容

private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
// 默认1.5倍扩容
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

查找

// 非空情况下使用for循环+equals实现,lastIndexOf同理
   public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

取值

//根据数组下标取值即可
 public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }
 E elementData(int index) {
        return (E) elementData[index];
    }

更新

// 将指定位置的值更新
public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

添加

// 尾部添加
public boolean add(E e) {
//容量检测
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
//添加元素到指定位置,
public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
//需要从index到尾部的所有元素往后移一位
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

删除

//删除指定位置元素
public E remove(int index) {
        rangeCheck(index);
// 注意这里,更新值是会变化的
        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
//需要从index到尾部的所有元素往前移一位
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work,清除尾部元素方便GC清理

        return oldValue;
    }
//删除指定元素
 public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
// 删除指定位置元素但是并没有返回值,也没有更新modCount
private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

批量删除

image.png

// complement为true,list删除x部分,反之list删除y部分
private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
	    //发生异常时,将list中未处理的部分复制到已处理的后面
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }

内部类

Itr

迭代器的实现类,实现类中有一个新方法 public void forEachRemaining(Consumer<? super E> consumer),这个方法是用 Lambda 实现之前的迭代器遍历。
Consumer<? super E> 这个函数接口接收一个泛型 T,没有返回值,所以 Lambda 形式的迭代器遍历方式为:

List a = new ArrayList();
Iterator it = a.iterator();
it.forEachRemaining(obj -> System.out.println(obj.toString()));

这个方法也是要改变迭代器游标的。所以只能使用一次,再次使用就没有元素可以用了。

ListItr

ListItr 继承自 Itr,他除了拥有 Itr 的全部方式,还拥有往前滑动游标的方法,意思是它是一个双向迭代器,可以往后滑,也可以往前。使用方法为:

List a = new ArrayList();
//游标从0开始
ListIterator it = a.listIterator();
//游标从2开始,即从第三个元素开始
ListIterator it = a.listIterator(2);

SubList

继承自 AbstractList,相当于一个拥有偏移量的 List,所有的操作都需要指定位置加上偏移量后进行。作用是成产一个 List 的子 List,但是内部保存有被截取的 list 的引用,所以对它的操作也会影响原有的 list。使用时需谨慎。
使用方法为:

List<String> l = new ArrayList<>();
        l.add("a");
        l.add("b");
        l.add("c");
        l.add("d");
        l.add("e");
        l.add("f");
        l.add("g");
        System.out.println(l);
        List<String> sl = l.subList(1,4);
        System.out.println(sl);
        sl.clear();
        System.out.println(sl);
        System.out.println(l);

ArrayListSpliterator

拆分器,实现了 Spliterator 接口。拆分器的作用为用于遍历和划分源元素的对象。拆分器覆盖的元素源可以是数组、集合、IO 通道或生成器函数。是 1.8 后为 Stream 提供支持的类。其方法跟迭代器差不多,tryAdvance(Consumer<? super T> action)next() 作用类似,不过 tryAdvance 可以直接传入一个方法对当前游标指向的元素进行操作,forEachRemaining 跟迭代器中的 forEachRemaining 使用方法和作用也一模一样,Spliterator<T> trySplit(); 可以拆分出一个一半大小的拆分器。

  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3167 引用 • 8207 回帖
  • 集合
    13 引用 • 8 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...