Priority queues - Java

1

How can I get the distances of the flights ordered according to these three conditions:

  • Priority 1: less than 500km
  • Priority 2: between 500 and 1000km
  • Priority 3: greater than 1000km

Using the comparator, I know that returns 1 for major, 0 equal and -1 for minors, but this is in comparisons of two objects, I can not find the way to be ordered according to those parameters.

 PriorityQueue<aeronaves> pil= new PriorityQueue();
 pil.offer(new aeronaves("avianca",500));
 pil.offer(new aeronaves("linux",400));
 pil.offer(new aeronaves("avianca",500));
 pil.offer(new aeronaves("tame",2000));
 pil.offer(new aeronaves("tame",500));
 pil.offer(new aeronaves("arca",200));
 while(!pil.isEmpty()){
      aeronaves ae= pil.poll();
      System.out.println("aerolina saliento: "+ae.getAerolinea()+"destino "+ae.getDestino());
 }


@Override
public int compareTo(aeronaves t) {
    if(t.getDestino<500){
        return -1;
    }
    if(t.getDestino>=500|| t.getDestino<1000){
        return 0;
    }else{
        return 1;
    }
}
    
asked by Michelle 24.11.2017 в 17:34
source

1 answer

-1

You are misusing the compareTo method. The way to implement the interface Comparable is as follows:

o1.compareTo(o2) must return an N value that complies:

  • N > 0 if o1 > o2
  • N = 0 if% co_of%
  • N < 0 if o1 == o2

So you could do the following:

In the aircraft class (by the way, the classes should always have the first letter in uppercase, it is the Java convention, and in this case it would be called Aircraft, in the singular), add the getPriority method:

int getPrioridad() {
    if (this.destino<500) return 1;
    if (this.destino<=1000) return 2;
    return 3;
}

And then you can implement your compareTo like this:

int compareTo(Aeronave t) {
    if (t==null) return 1; //un objeto inexistente siempre tendrá menor prioridad
    return this.getPrioridad() - t.getPrioridad();
}

Note: this does not order between Aircraft of the same priority, if the important thing is to order by destination you could simply return the difference between those values.

    
answered by 24.11.2017 в 18:22