在双端队列中,remove() 和 pop() 的区别是什么?

huangapple go评论67阅读模式
英文:

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&lt;String&gt; list = new LinkedList&lt;&gt;();
	list.push(&quot;first&quot;);
	list.push(&quot;second&quot;);
	list.push(&quot;third&quot;);
	
	System.out.println(list.remove());

Is equivalent to:

	Deque&lt;String&gt; list = new LinkedList&lt;&gt;();
	list.push(&quot;first&quot;);
	list.push(&quot;second&quot;);
	list.push(&quot;third&quot;);
	
	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>

huangapple
  • 本文由 发表于 2020年9月11日 18:57:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63845712.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定