LearnFrenzy
Sign in Take a free test

Data Structures in Java · Data Structures in Java Output Questions · Question 4

Printing a PriorityQueue before and after poll Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int x : new int[]{5, 1, 4, 2, 3}) pq.add(x);
        System.out.println(pq);
        pq.poll();
        System.out.println(pq);
    }
}
  • A [1, 2, 3, 4, 5] [2, 3, 4, 5]
  • B [1, 2, 4, 5, 3] [2, 3, 4, 5] Correct
  • C [5, 1, 4, 2, 3] [1, 4, 2, 3]
  • D [1, 2, 4, 5, 3] [3, 2, 4, 5]
Correct Answer: Option B

toString shows the heap array. Adding 2 sifts it above 5; 3 stays under 2. poll moves the last element (3) to the root and sifts it down past 2.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links