Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operation of RandomAccess in AbstractList.java

In java doc of RandomAccess class has written that "Marker interface used by List implementations to indicate that they support fast (generally constant time) random access. The primary purpose of this interface is to allow generic algorithms to alter their behavior to provide good performance when applied to either random or sequential access lists."

but I found some weird thing

this is the subList method in AbstractList.java in 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 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);
    }
}

SubList class implementation:

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 AbstractList class, RandomAccessSubList is useless, because it passes its data to the SubList class, and its operation is like

new SubList<>(this, fromIndex, toIndex)); 

in the subList method

like image 341
Pooya Avatar asked Jul 12 '12 10:07

Pooya


1 Answers

Since the root list is fast at accessing random indices, the sublist is also fast at doing it, so it makes sense to mark the sublist as RandomAccess as well.

SubList and RandomAccessSubList share the same implementation through inheritance, but one is not marked as RandomAccess, and the other is. That's why a subclass is useful.

like image 53
JB Nizet Avatar answered Nov 05 '22 07:11

JB Nizet