RandomAccess Interface, Why no methods?

2020-07-22 09:45发布

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?

2条回答
你好瞎i
2楼-- · 2020-07-22 10:07

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.

查看更多
Bombasti
3楼-- · 2020-07-22 10:29

This is a marker interface. It defines a behaviour or capability that does not make use of any extra methods.

In this case, it says that random access (already defined in the List interface) is not only possible, but also efficient. Code that uses List can switch between algorithms according to this.

One can argue if that is a good design decision. For example, the random access methods could have been removed from List (allowing just iteration), and placed into the RandomAccess interface instead. Similarly, the methods for the object serialization system could have been placed into the Serializable interface.

Also, only Lists can be RandomAccess?

I guess the interface could be used for other things as well, but it looks like it is only currently used by Lists.

What about Files?

There is a separate mechanism for random access to files (java.io.RandomAccessFile).

查看更多
登录 后发表回答