RandomAccess接口,为什么没有方法? [英] RandomAccess Interface, Why no methods?

查看:135
本文介绍了RandomAccess接口,为什么没有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读 Collections.shuffle(List)javadoc ,然后看看 RandomAccess javadoc


List实现使用的标记接口表示它们
支持快速(通常是恒定时间)随机访问。 [...]

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

我想知道为什么这个接口(如Serializable)没有方法?设计原因是什么?

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

即使只有列表实现这个接口,为什么不设置E get()作为方法?我知道不是每个列表都是随机访问,但是如果没有方法,如何使用这个接口?

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?

这样的东西:

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

此外,只有列表可以是RandomAccess?

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

推荐答案

Marker接口是一种先于注释的技术;

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.

在这种情况下,Shuffle在列表中的行为可能不同不支持快速随机访问。考虑如何清洗链表;很难,对吧?你不能只是说给我一个随机元素而不走遍列表,指向下一个元素。现在与ArrayList对比。获取一个随机元素要容易得多,因为列表的存储方式。

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.

没有办法限定如何存储列表或快速或慢速不同的访问模式可能在方法名称中。因此,Java使用标记接口来提供此信息。

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.

在这种情况下,ArrayList将是一个RandomAccess,而LinkedList不会。

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

EDIT

对标记界面和标记注释之间的区别感兴趣的人可以享受Item 37:定义类型,作者Joshua Bloch。

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.

这篇关于RandomAccess接口,为什么没有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆