# AbstractList的接口分析

image-20251223192325568

主要实现了AbstractCollection接口的一些抽象方法。

实现了 List接口的一些抽象定义的方法。

还有部分抽象方法在ArrayList类中实现。

# 接口定义

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {

}
1
2
3

# 抽象方法的实现

AbstractList类定义的add方法。

    public void add(int index, E element) {
        // 不支持的操作异常
        throw new UnsupportedOperationException();
    }
1
2
3
4

ArrayList类中的实现。

    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
1
2
3
4
5
6
7
8
9

为什么抛出异常的代码写在父类中?这个抛出异常的代码何时执行呢?

// 为什么在父类中抛出异常?add是实现list接口来的。
// 答:有些list子类可以不需要add这个方法操作。当不需要这个操作的子类对象进行操作会抛出异常
1
2
Last Updated: 4/3/2026, 6:47:37 AM