【问题标题】:In Deque, difference between remove() and pop()在 Deque 中,remove() 和 pop() 之间的区别
【发布时间】:2020-12-29 21:32:19
【问题描述】:

这段代码:

    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() 都删除第一个元素(头部)。那么,有两种不同方法的原因是什么?

【问题讨论】:

  • 当您调用 list.remove(); 时,它会调用 head 元素,因此您将获得类似于 list.pop();java.util.NoSuchElementException 现在如果您调用 list.remove("six");,那么它只会返回 false。跨度>

标签: java collections linked-list queue deque


【解决方案1】:

它与遗留接口有关。来自javadoc

Deques 也可以用作 LIFO(后进先出)堆栈。应优先使用此接口而不是旧的 Stack 类。当双端队列用作堆栈时,从双端队列的开头推送和弹出元素。 Stack 方法完全等同于 Deque 方法,如下表所示:

Stack 和 Deque 方法的比较

<em><strong>Stack Method</strong></em> | <em><strong>Equivalent Deque Method</strong></em>
<em>push(e)</em> | <em>addFirst(e)</em>
<em>pop()</em> | <em>removeFirst()</em>
<em>peek()</em> | <em>peekFirst()</em>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 2013-10-18
    • 2021-09-10
    相关资源
    最近更新 更多