gpt4 book ai didi

java - 在 ArrayDeque 中同时使用 push()、offer() 和 add() 方法会发生什么?

转载 作者:行者123 更新时间:2023-11-30 06:50:12 25 4
gpt4 key购买 nike

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

Stack 方法:push/poll/peek

Queue 方法:push/poll/peek

我在下面的代码块中所做的事情是,当在同一个对象中同时使用 offer、push 和 add 方法时,我试图理解 ArrayDeque 的行为。我编写的代码及其输出如下所示。 ArrayDeque 在调用 push() 方法后的行为是什么,它假设自己是一个堆栈,然后调用 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]

最佳答案

这是它一步一步做的

// 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 不同的主要目的是能够访问/添加元素在/到两端(头和尾)。

关于java - 在 ArrayDeque 中同时使用 push()、offer() 和 add() 方法会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41591223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com