在RandomAccess类的Java文档中写到
“List实现使用的Marker接口(interface)表示它们支持快速(通常是恒定时间)的随机访问。此接口(interface)的主要目的是允许通用算法更改其行为以在应用于随机访问或顺序访问列表时提供良好的性能。 ”
但是我发现了一些奇怪的东西
这是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,另一个未标记为RandomAccess。这就是子类有用的原因。