英文:
In Deque, difference between remove() and pop()
问题
这段代码:
Deque<String> list = new LinkedList<>();
list.push("first");
list.push("second");
list.push("third");
System.out.println(list.remove());
等同于:
Deque<String> list = new LinkedList<>();
list.push("first");
list.push("second");
list.push("third");
System.out.println(list.pop());
pop() 和 remove() 都用于移除第一个元素(头部元素)。那么,为什么会有两种不同的方法呢?
英文:
This code:
Deque<String> list = new LinkedList<>();
list.push("first");
list.push("second");
list.push("third");
System.out.println(list.remove());
Is equivalent to:
Deque<String> list = new LinkedList<>();
list.push("first");
list.push("second");
list.push("third");
System.out.println(list.pop());
Both pop() and remove() remove the first element (head). So, what's the reason for having two different methods?
答案1
得分: 4
涉及遗留接口。来自javadoc:
双端队列也可用作LIFO(后进先出)堆栈。应优先使用此接口,而不是遗留的Stack类。当双端队列用作堆栈时,元素从双端队列的开头推入和弹出。堆栈方法与Deque方法完全等效,如下表中所示:
堆栈方法与双端队列方法对比
<code>堆栈方法 | 等效双端队列方法</code>
<code>push(e) | addFirst(e)</code>
<code>pop() | removeFirst()</code>
<code>peek() | peekFirst()</code>
英文:
It has to do with legacy interfaces. From javadoc:
Deques can also be used as LIFO (Last-In-First-Out) stacks. This interface should be used in preference to the legacy Stack class. When a deque is used as a stack, elements are pushed and popped from the beginning of the deque. Stack methods are precisely equivalent to Deque methods as indicated in the table below:
Comparison of Stack and Deque methods
<code>Stack Method | Equivalent Deque Method</code>
<code>push(e) | addFirst(e)</code>
<code>pop() | removeFirst()</code>
<code>peek() | peekFirst()</code>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论