2017-01-11 97 views
-2

ArrayDeque有堆棧和隊列的方法。主要用於棧和隊列的方法是在下面的那些:在ArrayDeque中同時使用push(),offer()和add()方法時會發生什麼?

Stack方法:push/poll/peek

Queue方法:push/poll/peek

,我的已經做了的事下面的代碼塊是這樣的,我試圖理解ArrayDeque同時提供的行爲,push和add方法在同一個對象中使用。我寫的代碼和它的輸出如下。在調用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] 
+0

這裏有什麼奇怪的? –

+0

閱讀javadoc。所有這些方法的作用在那裏都有明確的解釋。 –

回答

0

下面是它一步

// 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] 

確實步請記住,一個Deque的主要目的不像QueueStack是有能力訪問/添加元素在/到兩個結束(頭部和尾部)。

+0

基本上這個https://docs.oracle.com/javase/7/docs/api/java/util/ArrayDeque.html –

0

1.offer - 此方法在此雙端隊列的末尾插入指定的元素。 2.add - 此方法在此雙端隊列的末尾插入指定的元素。 3.push-這個方法將一個元素推送到由這個雙端隊列表示的堆棧上。 4.addFirst - 此方法在此雙端隊列的前端插入指定的元素。 5.addLast - 此方法在此雙端隊列的末尾插入指定的元素。

相關問題