Java Reference
In-Depth Information
Listing 12-16. A ComparablePerson Class
// ComparablePerson.java
package com.jdojo.collections;
public class ComparablePerson extends Person implements Comparable {
public ComparablePerson(int id, String name) {
super(id, name);
}
@Override
public int compareTo(Object o) {
ComparablePerson cp = (ComparablePerson) o;
int cpId = cp.getId();
String cpName = cp.getName();
if (this.getId() < cpId) {
return -1;
}
if (this.getId() > cpId) {
return 1;
}
if (this.getId() == cpId) {
return this.getName().compareTo(cpName);
}
// Should not reach here
return 0;
}
}
Listing 12-17 demonstrates how to use a priority queue.
Listing 12-17. Using a Priority Queue
// PriorityQueueTest.java
package com.jdojo.collections;
import java.util.Queue;
import java.util.PriorityQueue;
public class PriorityQueueTest {
public static void main(String[] args) {
Queue<ComparablePerson> pq = new PriorityQueue<>();
pq.add(new ComparablePerson(1, "John"));
pq.add(new ComparablePerson(4, "Ken"));
pq.add(new ComparablePerson(2, "Richard"));
pq.add(new ComparablePerson(3, "Donna"));
pq.add(new ComparablePerson(4, "Adam"));
System.out.println("Priority queue: " + pq);
Search WWH ::




Custom Search