Author: techfox9

How to use PriorityQueue

Friday, April 3rd, 2015 @ 11:03 pm

From http://stackoverflow.com/questions/683041/java-how-do-i-use-a-priorityqueue

[java]

// TestPQ.java
import java.util.Comparator;
import java.util.PriorityQueue;

public class TestPQ {
public static void main(String[] args) {
Comparator comparator = new StringLengthComparator();
PriorityQueue queue =
new PriorityQueue(10, comparator);
queue.add(“short”);
queue.add(“very long indeed”);
queue.add(“medium”);
while (queue.size() != 0) {
System.out.println(queue.remove());
}
}
}

[/java]

[java]

// StringLengthComparator.java
import java.util.Comparator;

public class StringLengthComparator implements Comparator {
@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() < y.length()) { return -1; } if (x.length() > y.length()) {
return 1;
}
return 0;
}
}

[/java]

Algorithms, Java


 


Comments are closed.