Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does RandomAccess have any value in modern day Java?

There is that peculiar interface which is documented as such (extracts only):

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.

The listed implementations are (as of JDK 8):

ArrayList, AttributeList, CopyOnWriteArrayList, RoleList, RoleUnresolvedList, Stack, Vector

Two of which (the latter two, in fact) are obsolete in any code you would produce today.

Now, as a word of warning, my research has been so NOT extensive that I am asking this question out of a whim. Is there any use case at this point in time where one would see the need to use this interface, or even implement it?

like image 603
fge Avatar asked Sep 29 '22 12:09

fge


1 Answers

This marker interface could be useful for algorithm implementors. Lists which implement this interface can be handled differently from the lists without random access.

For example, "if the list is random-access, use binary search, otherwise use linear search."

One example is Guava's Lists.transform:

public static <F, T> List<T> transform(
        List<F> fromList, Function<? super F, ? extends T> function) {
   return (fromList instanceof RandomAccess)
       ? new TransformingRandomAccessList<F, T>(fromList, function)
       : new TransformingSequentialList<F, T>(fromList, function);
}
like image 104
Alex Shesterov Avatar answered Oct 03 '22 07:10

Alex Shesterov