The java document of the RandomAccess class states that the "Token interface used by List implementations to indicate that they support fast (usually constant) random access. The main purpose of this interface is to allow generic algorithms to change their behavior to provide good performance when applied to random or sequential access lists. "
but I found some strange thing
this is the subList method in AbstractList.java in the java.util package
public List<E> subList(int fromIndex, int toIndex) {
return (this instanceof RandomAccess ?
new RandomAccessSubList<>(this, fromIndex, toIndex) :
new SubList<>(this, fromIndex, toIndex));
}
Implementation of the RandomAccessSubList class:
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);
}
}
implementation of the SubList class:
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;
}
and I think that in the AbstractList class, RandomAccessSubList is useless because it passes its data to the SubList class and its operation is similar to
new SubList<>(this, fromIndex, toIndex));
in subList method