【问题标题】:What happens when using push(), offer() and add() methods in ArrayDeque at the same time?在 ArrayDeque 中同时使用 push()、offer() 和 add() 方法会发生什么?
【发布时间】:2017-05-26 06:20:45
【问题描述】:

ArrayDeque 有栈和队列的方法。最常用的栈和队列方法如下:

Stack 方法:push/poll/peek

Queue 方法:push/poll/peek

我在下面的代码块中所做的事情是,当在同一个对象中同时使用提供、推送和添加方法时,我试图了解 ArrayDeque 的行为。我编写的代码及其输出如下所示。在调用push() 方法后ArrayDeque 的行为是什么,它假设自己是一个堆栈,然后调用offer() 方法,它被称为队列方法。

Deque<Integer> arrayDeque = new ArrayDeque<>(); 

arrayDeque.add(3);
arrayDeque.push(4);
arrayDeque.offer(6);
arrayDeque.addFirst(2);
arrayDeque.addLast(5);
arrayDeque.addFirst(1);
System.out.println("ArrayDeque: " + arrayDeque.toString());

输出是:

ArrayDeque: [1, 2, 4, 3, 6, 5]

【问题讨论】:

  • 这有什么奇怪的?
  • 阅读 javadoc。那里清楚地解释了所有这些方法的作用。

标签: java collections arraydeque


【解决方案1】:

1.offer-此方法在此双端队列的末尾插入指定元素。 2.add-这个方法在这个双端队列的末尾插入指定的元素。 3.push——这个方法将一个元素压入这个双端队列所代表的栈中。 4.addFirst——这个方法在这个双端队列的前面插入指定的元素。 5.addLast-该方法在这个双端队列的末尾插入指定的元素。

【讨论】:

    【解决方案2】:

    这是一步一步的作用

    // Add 3 at the tail of this deque
    arrayDeque.add(3); -> [3]
    // Add 4 at the head of this deque
    arrayDeque.push(4); -> [4, 3]
    // Add 6 at the tail of this deque
    arrayDeque.offer(6); -> [4, 3, 6]
    // Add 2 at the head of this deque
    arrayDeque.addFirst(2); -> [2, 4, 3, 6]
    // Add 5 at the tail of this deque
    arrayDeque.addLast(5); -> [2, 4, 3, 6, 5]
    // Add 1 at the head of this deque
    arrayDeque.addFirst(1); -> [1, 2, 4, 3, 6, 5]
    

    请记住,DequeQueueStack 不同的主要目的是能够访问/添加元素在/到两端(头和尾巴)。

    【解决方案3】:

    你不明白什么?

    你能解释一下ArrayDeque在调用push()方法后的行为吗,它假设自己是一个堆栈,然后调用offer()方法,在JavaDoc中被称为队列方法

    查看 Javadoc:https://docs.oracle.com/javase/7/docs/api/java/util/ArrayDeque.html

    push方法在开头插入,offer在结尾插入。

    【讨论】:

      【解决方案4】:

      Nicolas Filotto 的答案是正确的。 我发现源代码文件中的“尾巴”解释是错误的。它说添加=推送。但是,在函数实现中,add = addLast,push = addFirst。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-14
        • 2018-05-17
        • 1970-01-01
        • 2015-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-04
        相关资源
        最近更新 更多