4
I’m trying to understand why the native mode of java is not performing the comparison, I don’t know where I’m going wrong.
MAIN
// EXERCICIO PARA COMPARAR DOIS OBJETOS, USANDO CLASSE NATIVA DE COMPARAÇÃO DO JAVA
public static void main(String[] args) {
FilaComPrioridade<Paciente> fila = new FilaComPrioridade<>();
// CLASSE ANONIMA DENTRO DO NOSSO PROJETO.
Queue<Paciente> filaComPrioridade = new PriorityQueue<>(new Comparator<Paciente>() {
@Override
public int compare(Paciente p1, Paciente p2) {
return Integer.valueOf(p1.getPrioridade()).compareTo(p2.getPrioridade());
}
});
filaComPrioridade.add(new Paciente("A", 2));
filaComPrioridade.add(new Paciente("B1", 1));
filaComPrioridade.add(new Paciente("B2", 1));
filaComPrioridade.add(new Paciente("B3", 1));
filaComPrioridade.add(new Paciente("B4", 1));
filaComPrioridade.add(new Paciente("C", 3));
fila.enfileira(new Paciente("A", 2));
fila.enfileira(new Paciente("B1", 1));
fila.enfileira(new Paciente("B2", 1));
fila.enfileira(new Paciente("B3", 1));
fila.enfileira(new Paciente("B4", 1));
fila.enfileira(new Paciente("C", 3));
System.out.println(filaComPrioridade);
System.out.println(fila);
}
}
Imprint
[Patient [name=B1, priority=1], Patient [name=B3, priority=1], Patient [name=B2, priority=1], Patient [name=A, priority=2], Patient [name=B4, priority=1], Patient [name=C, priority=3]]
[Patient [name=B1, priority=1], Patient [name=B2, priority=1], Patient [name=B3, priority=1], Patient [name=B4, priority=1], Patient [name=A, priority=2], Patient [name=C, priority=3]]
Philanthropy class:
package pt.estruturadedados.base.fila;
public class FilaComPrioridade<T> extends Fila<T> {
@Override
public void enfileira(T elemento) {
Comparable<T> chave = (Comparable<T>) elemento;
int i;
for (i = 0; i < this.tamanho; i++) {
if (chave.compareTo(this.elementos[i]) < 0) {
break;
}
}
this.adiciona(i, elemento);
}
}
CompareTo
in the "NOT NATIVE" Manual Patient Class (Second Impression)
@Override
public int compareTo(Paciente o) {
return Integer.valueOf(this.getPrioridade()).compareTo(o.getPrioridade()); //Forma mais elegante de fazer.
}
Excellent answer, I learned something new. It is understandable that the
PriorityQueue
use a structure of heap internally, but honestly I find a design well severe API. It would be better to make a override of the methoditerator()
to return items in the correct order (making it clear to the user that the interaction time is not linear). What must it take for people to fall for pranks likefor (Paciente p : filaComPrioridade)
is not in the comic book.– Anthony Accioly