为什么java链表实现使用接口deque?
我在查看LinkedList的java实现,发现了这个:
public class LinkedList<E>
extends AbstractSequentialList<E> implements List<E>,
Deque<E>, Cloneable, java.io.Serializable
Why should a LinkedList support the Deque interface? 我理解将元素添加到链表末尾的愿望,但这些方法应该包含在 List 接口中。
I was looking at the java implementation of LinkedList, and found this:
public class LinkedList<E>
extends AbstractSequentialList<E> implements List<E>,
Deque<E>, Cloneable, java.io.Serializable
Why should a LinkedList support the Deque interface?
I understand the desire to add elements to the end of the linked list, but those methods should have been incuded in the List interface.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
LinkedList
实现恰好满足Deque
契约,那么为什么不让它实现该接口呢?The
LinkedList
implementation happens to to satisfy theDeque
contract, so why not make it implement the interface?正如 JavaDocs 中所述:
这些操作允许将链表用作堆栈、队列或双端队列。
List 接口只是一个 List,即您可以添加或删除。因此,List 接口的基本实现必须只提供那些简单的方法,例如 ArrayList。 Deque接口是双端队列,iava的LinkedList IS-A双端队列。
As the JavaDocs states:
These operations allow linked lists to be used as a stack, queue, or double-ended queue.
The List interface is just a List i.e. you can add or remove. So a basic implementation of the List interface has to just provide those simple methods e.g. ArrayList. The Deque interface is the double ended Queue and iava's LinkedList IS-A Double Ended Queue.
IIRC,
deque
代表双端队列
。在您提到的情况下,将通用List
定义为双端队列是不合逻辑的。例如,ArrayList
不是为Deque
接口设计的。插入在列表的末尾是有效的,但绝对不是在列表的开头(因为我认为这会导致整个数组的重新分配)。另一方面,
LinkedList
是为Deque
接口完美设计的,因为它是一个双链表。IIRC,
deque
stands fordouble end queue
. In the case you mention, it's not logical to define a genericList
as a deque. For instance, anArrayList
is not designed for theDeque
interface. Insertions will be efficient in the end of the list, but absolutely not at its beginning (because it will cause the re-allocation of a whole array, I think).The
LinkedList
is, on the other end, perfectly designed for theDeque
interface, as it is a double linked list.由于双端队列可能使用
LinkedList
以外的其他方式实现,并且代码可能依赖于任何具有此类功能的东西,因此Deque
接口需要单独提供。List
本身不应该实现/扩展Deque
,因为在列表开头添加/删除可能不是每个实现都能(轻松)支持的。Because a double-ended queue might be implemented using something other than a
LinkedList
and one's code may depend on anything with such functionality, so theDeque
interface needs to be available separately.List
should not itself implement/extendDeque
because adding to/removing from the start of a list may not be something that can be (easily) supported by every implementation.