Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RandomAccess Interface, Why no methods?

I was reading Collections.shuffle(List) javadoc and then took a look at the RandomAccess javadoc:

Marker interface used by List implementations to indicate that they support fast (generally constant time) random access. [...]

I am wondering why this interface (like Serializable) does not have methods? What is the design reason for this?

Even if only Lists "implement" this interface, why not setting E get() as a method? I know that not every list is random access but how can I use this interface if there is no methods?

Something like this:

if(object instanceof RandomAccess){
    // should I cast it if no operations can be done? why?
}

Also, only Lists can be RandomAccess? What about Files?

like image 248
ElderMael Avatar asked Apr 11 '26 04:04

ElderMael


1 Answers

A "Marker" interface is a technique that predates annotations; it is meant to mark a Class as conforming to some standard, where the standard isn't about methods.

In this case, Shuffle may act differently on a list that doesn't support quick random access. Consider how you would shuffle a linked list; it's hard, right? You can't just say "get me a random element" without walking through the list, following pointers to the next element. Now contrast this with an ArrayList. Getting a random element is much easier, because of the way the list is stored.

There isn't a way to qualify "how the list is stored" or "how fast or slow different access patterns might be" in a method name. So instead, Java uses marker interfaces to provide this information.

In this case, ArrayList would be a RandomAccess, and LinkedList would not.

EDIT

Those interested in the differences between marker interfaces and marker annotations would enjoy Item 37:"Use marker interfaces to define types" in Effective Java 2nd Edition by Joshua Bloch.

like image 128
Cory Kendall Avatar answered Apr 13 '26 07:04

Cory Kendall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!