在RandomAccess类的java文档中"List实现使用的标记接口,表示它们支持快速(通常是恒定时间)随机访问。该接口的主要目的是允许通用算法改变其行为,以便在应用于随机或顺序访问列表时提供良好的性能。"
但我发现了一些奇怪的东西
这是java.util包中AbstractList.java中的subList方法
public List<E> subList(int fromIndex, int toIndex) {
return (this instanceof RandomAccess ?
new RandomAccessSubList<>(this, fromIndex, toIndex) :
new SubList<>(this, fromIndex, toIndex));
}
RandomAccessSubList类的实现:
class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
super(list, fromIndex, toIndex);
}
public List<E> subList(int fromIndex, int toIndex) {
return new RandomAccessSubList<>(this, fromIndex, toIndex);
}
}
SubList类实现:
SubList(AbstractList<E> list, int fromIndex, int toIndex) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
if (toIndex > list.size())
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");
l = list;
offset = fromIndex;
size = toIndex - fromIndex;
this.modCount = l.modCount;
}
我认为在AbstractList类中,RandomAccessSubList是无用的,因为它将数据传递给SubList类,并且它的操作类似于
new SubList<>(this, fromIndex, toIndex));
在subList方法
由于根列表访问随机索引的速度很快,子列表也很快,因此将子列表标记为RandomAccess也是有意义的。
SubList和RandomAccessSubList通过继承共享相同的实现,但一个没有标记为RandomAccess,另一个标记为。这就是子类有用的原因。