RandomAccess Interface, Why no methods?

岁酱吖の 提交于 2019-12-04 12:30:49

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.

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!