Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Use the constructor overload which takes a <code>Comparator&lt;? super E&gt; comparator</code> and pass in a comparator which compares in the appropriate way for your sort order. If you give an example of how you want to sort, we can provide some sample code to implement the comparator if you're not sure. (It's pretty straightforward though.)</p> <p>As has been said elsewhere: <code>offer</code> and <code>add</code> are just different interface method implementations. In the JDK source I've got, <code>add</code> calls <code>offer</code>. Although <code>add</code> and <code>offer</code> have <em>potentially</em> different behaviour in general due to the ability for <code>offer</code> to indicate that the value can't be added due to size limitations, this difference is irrelevant in <code>PriorityQueue</code> which is unbounded.</p> <p>Here's an example of a priority queue sorting by string length:</p> <pre><code>// Test.java import java.util.Comparator; import java.util.PriorityQueue; public class Test { public static void main(String[] args) { Comparator&lt;String&gt; comparator = new StringLengthComparator(); PriorityQueue&lt;String&gt; queue = new PriorityQueue&lt;String&gt;(10, comparator); queue.add("short"); queue.add("very long indeed"); queue.add("medium"); while (queue.size() != 0) { System.out.println(queue.remove()); } } } // StringLengthComparator.java import java.util.Comparator; public class StringLengthComparator implements Comparator&lt;String&gt; { @Override public int compare(String x, String y) { // Assume neither string is null. Real code should // probably be more robust // You could also just return x.length() - y.length(), // which would be more efficient. if (x.length() &lt; y.length()) { return -1; } if (x.length() &gt; y.length()) { return 1; } return 0; } } </code></pre> <p>Here is the output: </p> <blockquote> <p>short</p> <p>medium</p> <p>very long indeed</p> </blockquote>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload