I created a DeQueue as follws
Deque<Integer> deque = new ArrayDeque<Integer>(8);
// use add() method to add elements in the deque
deque.add(20);
deque.add(30);
deque.addLast(12);
deque.add(18);
deque.addFirst(22);
deque.add(24);
// let us print all the elements available in deque
for (Integer number : deque) {
System.out.println("Number = " + number);
}
The expected output is:
Number = 22
Number = 20
Number = 30
Number = 18
Number = 24
Number = 12
But the actual output is :
Number = 22
Number = 20
Number = 30
Number = 12
Number = 18
Number = 24
Anybody please explain this?
addLast
doesn't somehow maintain a notion of "this should be last" forever - it just adds to the end of the current dequeue. It's equivalent to add
, as documented.
So if we look at the values at each step, we have:
deque.add(20); // Contents: 20
deque.add(30); // Contents: 20, 30
deque.addLast(12); // Contents: 20, 30, 12
deque.add(18); // Contents: 20, 30, 12, 18
deque.addFirst(22); // Contents: 22, 20, 30, 12, 18
deque.add(24); // Contents: 22, 20, 30, 12, 18, 24
... which exactly corresponds to the output you got.
See more on this question at Stackoverflow