# AbstractList的接口分析

主要实现了AbstractCollection
实现了 List
还有部分抽象方法在ArrayList
# 接口定义
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
}
1
2
3
2
3
# 抽象方法的实现
AbstractList
public void add(int index, E element) {
// 不支持的操作异常
throw new UnsupportedOperationException();
}
1
2
3
4
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
2
3
4
5
6
7
8
9
为什么抛出异常的代码写在父类中?这个抛出异常的代码何时执行呢?
// 为什么在父类中抛出异常?add是实现list接口来的。
// 答:有些list子类可以不需要add这个方法操作。当不需要这个操作的子类对象进行操作会抛出异常
1
2
2