Page 1 of 1

About Question enthuware.ocpjp.v8.2.1133 :

Posted: Fri Apr 13, 2018 11:17 pm
by shamran99
Hi,

The following statement confused me.

"Since Stack is a LIFO structure (Last In First Out i.e. add to the front and remove from the front), it provides methods push(e) and pop() for this purpose, where push adds to the front and pop removes from the front"

I think it should be like "where push adds to the back and pop removes from the back"

For example, I tried the below code..

Code: Select all

Deque<Integer> q = new LinkedList<>(); 
//Stack<Integer> q = new Stack<Integer>(); 
q.push(1);
q.push(2);
q.push(3);
System.out.println(q);
When stack is commented it prints [3,2,1] and when the Deque is commented it prints [1,2,3].
I believe its because, deque is pushing in the front and stack is pushing in the back. Am I wrong?

Regards,
Shamran.

Re: About Question enthuware.ocpjp.v8.2.1133 :

Posted: Sat Apr 14, 2018 9:38 pm
by admin
When you try to print q, the string that is printed is generated by the toString method. This method is just returning the contents of the internal data structure used by LinkedList and Stack. This has no bearing on the semantic notion of "front" and "back". Ideally, we don't talk of front and back with respect to stacks, we talk of "top" and "bottom".

But if you compare stack and queue, then yes, top of the stack is similar to front of the queue. In that sense, logically, the given statement (push adds to the front and pop removes from the front) is correct. You should test that by calling pop method and not by printing the out of toString. You will get the same output with Deque and Stack.

HTH,
Paul.

Re: About Question enthuware.ocpjp.v8.2.1133 :

Posted: Mon Oct 26, 2020 9:52 am
by RogierA
What is the difference between pollfirst and poll? (i assumed 1 could not exist since there would be no difference)

Re: About Question enthuware.ocpjp.v8.2.1133 :

Posted: Wed Oct 28, 2020 4:55 am
by admin
pollFirst is declared in Deque interface while poll is declared in Queue. Since Deque is a double sided queue (it extends Queue) and so it has both pollFirst and poll.