What Is RandomAccess Interface?

This interface is a member of the Java Collections Framework. This interface introduced in Java version 1.4. It marks the implementations of list which can be accessed randomly. This way a caller can either access the data randomly if that is efficient, or use another means if it is not.

Marker interface used by List implementations to indicate that they support fast random access. The access is generally constant time.

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. Algorithms are used to manipulate random access lists and sequential access lists. The same algorithms may give different performance results for these two type of lists. Generic list algorithms should check whether the given list is an instance of this interface before applying an algorithm that would provide poor performance if it were applied to a sequential access list. In this case algorithms should change their behavior if necessary to guarantee acceptable performance.

According to Java documentation, a List implementation should implement this interface if, for typical instances of the class, this loop:

for (int i=0, n=list.size(); i < n; i++)

runs faster than this loop:

for (Iterator i=list.iterator(); i.hasNext(); )

In client code, you can check whether the collection is instance of RandomAccess and then only perform the Random access operations.

Collection<Integer> c = new ArrayList<Integer>();
if (c instanceof RandomAccess){
        System.out.println("use random access algorithm");//fast access date
        System.out.println("use sequential access algorithm");