Home > Java > javaTutorial > body text

Why is My PriorityQueue\'s toString Output Disordered Despite a Correct Comparator?

Patricia Arquette
Release: 2024-10-30 14:11:26
Original
365 people have browsed it

Why is My PriorityQueue's toString Output Disordered Despite a Correct Comparator?

PriorityQueue Order Discrepancy in toString Output

The issue stems from the incorrect usage of PriorityQueue's toString method when the comparator doesn't sort the elements as expected.

Comparator Error

In the given comparator HuffmanComparator, the code should be modified as follows to prioritize nodes with lower frequency:

<code class="java">public int compare(TreeNodeHuffman p1, TreeNodeHuffman p2) {
  if (p1.frequency > p2.frequency) return -1;
  if (p1.frequency < p2.frequency) return 1;
  return 0;
}</code>
Copy after login

toString and Polling

Although the comparator is now correct, PriorityQueue's toString method does not guarantee the elements are fully sorted. To obtain the sorted elements, we should poll the items one by one using a while loop:

<code class="java">while (!queue.isEmpty()) {
  System.out.println(queue.poll());
}</code>
Copy after login

This approach ensures the heap structure is fixed during each call to poll, resulting in the desired order of elements in the output.

The above is the detailed content of Why is My PriorityQueue\'s toString Output Disordered Despite a Correct Comparator?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template