LearnFrenzy
Sign in Take a free test

Data Structures in Java · Data Structures in Java – Find the Error · Question 8

Error: a max-heap comparator returning boolean Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> a > b);
        maxHeap.add(3);
        maxHeap.add(9);
        System.out.println(maxHeap.peek());
    }
}
  • A PriorityQueue cannot be a max-heap
  • B A Comparator must return an int (negative, zero or positive), not a boolean; use (a, b) -> Integer.compare(b, a) or Comparator.reverseOrder() Correct
  • C Lambdas cannot be passed to constructors
  • D add must be offer
Correct Answer: Option B

compare returns int, so the boolean lambda does not match Comparator<Integer> and javac cannot infer the PriorityQueue type.

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