Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

SCJP CH 7 Q9 PQ

 
ali kamran
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
Have a question with regards to Queue,Priority queue.Question below from K&B scjp book Ch 7 Q9
<code>
9. Given the proper import statement(s), and
13. PriorityQueue<String> pq = new PriorityQueue<String>();
14. pq.add("2");
15. pq.add("4");
16. System.out.print(pq.peek() + " ");
17. pq.offer("1");
18. pq.add("3");
19. pq.remove("1");
20. System.out.print(pq.poll() + " ");
21. if(pq.remove("2")) System.out.print(pq.poll() + " ");
22. System.out.println(pq.poll() + " " + pq.peek());

</code>
What is the result?
A. 2 2 3 3
B. 2 2 3 4
C. 4 3 3 4
D. 2 2 3 3 3
E. 4 3 3 3 3
F. 2 2 3 3 4
G. Compilation fails
H. An exception is thrown at runtime

What I Expected:
Now I would expect it adds 2-->then 4-->then peek so display 2 -->then add 1 and 3 so now we have [2,4,1,3] --> remove 1 -->poll so remove 2 now [4,3] -->if fails -->then poll and peek so display 4 and 3.Thus answer should be 2 2 4 3

What It is:
2 2 3 4.

What I did:
When I popped it in code I see 3 ahead of 4


<code>
package TEST2;

import java.util.PriorityQueue;
import java.util.TreeMap;

public class Q9 {
public static void main(String args[])
{
TreeMap<String,String> mymap= new TreeMap<String,String>();

PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("2");
pq.add("4");
System.out.println("pq is"+pq);
System.out.println(pq.peek() + " ");
pq.offer("1");
pq.add("3");
System.out.println("pq is"+pq);
pq.remove("1");
System.out.println("3rd pq is"+pq);
System.out.println(pq.poll() + " ");
if(pq.remove("2"))
System.out.println(pq.poll() + " ");
System.out.println(pq.poll() + " " + pq.peek());


}


}

</code>

What the issue is:
In the syso why do I see 1 and 3 inserted ahead of 2 and 4 ?
Somebody please have the patience to explain me .Much appreciated....
 
Anayonkar Shivalkar
Bartender
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello ali kamran,

Please, UseCodeTags. Without them, code becomes really difficult to read. Also, please TellTheDetails. If you have any dispute with the actual output, please let us know what the output should be (as per your way of thinking) and why.

I hope this helps.

And Welcome to CodeRanch!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic