Video in progress
What is the RandomAccess marker interface for, and how does code that walks a List by index slow down with a LinkedList?
RandomAccess is an interface with no methods, a tag meaning "get(i) is fast". ArrayList implements it and LinkedList doesn't. JDK algorithms pick index-based or iterator-based access based on it, while an indexed for loop turns into O(n²) on a LinkedList.
📖 Answer
The classic bug:
void export(List<Row> rows) {
for (int i = 0; i < rows.size(); i++) {
write(rows.get(i)); // on a LinkedList every get(i) walks along the list
}
}
With an ArrayList, 100,000 rows are written instantly. If someone upstream switches to new LinkedList<>(), or a library returns a LinkedList, every get(i) takes on average n/4 steps (it walks from the nearer end), billions of steps in total. The method hasn't changed, but the endpoint takes minutes to respond.
The JDK itself guards against this. Collections.binarySearch, shuffle, reverse and fill have a check like this inside:
if (list instanceof RandomAccess || list.size() < THRESHOLD) {
// by index
} else {
// with a ListIterator
}
The same rule applies to your own helper methods:
- for a
Listof unknown type, use for-each or an iterator, which is O(n) on any list; - if you really need the index (say, walking two lists side by side), check for
RandomAccessor first make a copy withnew ArrayList<>(list); List.of,Arrays.asListandArrayList.subListareRandomAccesstoo.
The interface was added in Java 1.4, and its only job is to be a tag for an instanceof check. If you write your own array-backed list on top of AbstractList, don't forget to add it, or the Collections methods will pick the slow path.
Sign up to mark studied questions and save your progress.