[code]
import java.util.*;
class Par < T extends Comparable < T > , U > implements Comparable < Par < T,U > > {
private T t;
private U u;
public Par (T t, U u) { this.t = t; this.u = u; }
public T getT() { return t; }
public U getU() { return u; }
public int compareTo (Par < T,U > obj) {
return t.compareTo (obj.getT());
}
public String toString() { return “{” + t + “,” + u + “}”; }
}
class Pessoa {
private String nome;
public Pessoa (String nome) { this.nome = nome; }
public String toString() { return nome; }
}
class ExemploPriorityQueue {
public static void main(String[] args) {
PriorityQueue < Par < Integer,Pessoa > > pq = new PriorityQueue < Par < Integer,Pessoa > > ();
// A diferença entre “add” e “offer” é que add lança uma exceção se a fila estiver cheia,
// e offer náo lança a tal exceção, mas isso é só para outras classes que implementam Queue.
// Para PriorityQueue não há diferença alguma.
pq.add (new Par < Integer,Pessoa > (10, new Pessoa (“Gabriel O Pensador”)));
pq.offer (new Par < Integer,Pessoa > (3, new Pessoa (“Gilberto Kassab”)));
pq.add (new Par < Integer,Pessoa > (2, new Pessoa (“Jose Serra”)));
pq.add (new Par < Integer,Pessoa > (3, new Pessoa (“Cesar Maia”)));
pq.add (new Par < Integer,Pessoa > (2, new Pessoa (“Sergio Cabral”)));
pq.add (new Par < Integer,Pessoa > (1, new Pessoa (“Luis Inacio Lula da Silva”)));
// Iterando sobre a priority queue - note que a ordem é indefinida;
//
for (Par < Integer, Pessoa > p : pq) {
System.out.println (p);
}
// Copiando a priority queue só para fazer uma demonstração.
PriorityQueue < Par < Integer,Pessoa > > pqCopia = new PriorityQueue < Par < Integer,Pessoa > > ();
pqCopia.addAll (pq);
// Imprimindo a priority queue na ordem de prioridade.
// Note que a ordem de dois elementos com a mesma
// prioridade é indefinida. Infelizmente, imprimir uma priority queue a destrói,
// porque temos de usar "poll", que remove sempre o primeiro elemento da fila.
System.out.println ("-------------");
for (Par < Integer,Pessoa > p = pq.poll(); p != null; p = pq.poll()) {
System.out.println (p);
}
// Imprimindo a priority queue, mas usando peek e remove.
System.out.println ("-------------");
for (Par < Integer,Pessoa > p = pqCopia.peek(); p != null; ) {
System.out.println (p);
pqCopia.remove (p);
p = pqCopia.peek();
}
// Mostrando que "element" lança uma exceção se a priority queue estiver vazia.
// "element" é semelhant a "peek", exceto por esse fato.
try {
Par < Integer, Pessoa > p = pq.element();
} catch (NoSuchElementException ex) {
ex.printStackTrace();
}
}
}[/code]