Im trying to use the override comparator method of priorityqueue and i want to achieve the following:
i have the current list:
RG3
PR1
PR2
RG4
RG1
RG2
the RG refers to a regular person and the PR refers to a person with priority, the numbers represent the turns. what i want is to get a First in first out order except when is a priority person wich will go to the top of the queue in his turn. so in the list i want the following result
PR1
PR2
RG1
RG2
RG3
RG4
heres what ive done until now:
Queue<Ficha> cola = new PriorityQueue<>(6, idComparator);
while (!list.isEmpty()) //this list is the unsorted list.
{
aux = list.remove(0);
cola.add(aux); // adds it to the priority queue
}
while(!cola.isEmpty())
{
aux = cola.poll();
System.out.println(aux.getCod_priority()+aux.getTurn()); // this shows me the order of the queue
}
}
public static Comparator<Ficha> idComparator = new Comparator<Ficha>()
{
@Override
public int compare(Ficha f1, Ficha f2) {
return (int) ((f1.getTurn()+prioridad(f1.getCod_priority())) - (f2.getTurn()+prioridad(f2.getCod_priority())));
}
};
private static long prioridad(String cod_priority) // this method i use it to give the cod_priority a int value to compare
{
if(cod_tipo_ficha=="PR")
{
return 10000;
}
else
{
return 1;
}
}
and when i run it i get the following order:
PR1
RG1
RG2
PR2
RG3
RG4
i know my problem is in the comparator method but i dont know how to achieve the queue that i want.
i know theres a lot of question related of how to compare but the only answers i see is when you compare strings. and this one i need to compare the priority string and the int.
Just change cod_tipo_ficha=="PR" to
if("PR".equals(cod_tipo_ficha)) {
...
}
Should work