exercice priority queue Comparable To

0

Someone can explain to me what behavior has the comparable method To go putting objects to the queue with priority, according to I believe if it returns a negative the greater object is the one that is passed as a parameter. But in this exercise because it works the other way around, I get the answer that the method invokes, but it returns a minus 1. I do not understand why it works. If someone can explain it to me, thank you.

import java.util.PriorityQueue;
  public class TestEx_c_jun14
{
public static void main(String args[])
{
 PriorityQueue<Atomo> q=new PriorityQueue();
int n[]={100,2,10,5,50,20,25,3,1};
for(int i=0; i<n.length; i++)
q.offer(new Atomo(n[i]));
System.out.println(q.peek().toString());
}
}
class Atomo implements Comparable<Atomo>
 {
 int atributo;
 public Atomo(int n) {
 atributo=n;
}
  public int getAtributo() { return atributo; }
  public String toString() { return Integer.toString(atributo); }
  public int compareTo(Atomo e) {
   int c = 0;
   if(e.getAtributo() % getAtributo() == 0)
     c = +1;
   else
     c = -1;
   return c;
 }
}
    
asked by gabriel gomez 09.01.2017 в 23:30
source

1 answer

0

Implementing the Comparable interface is necessary, for example, to create ordered lists. To give the possibility to the programmer to define in which case an object is considered less, equal or more than another object in sequence context, the method is defined

public int compareTo(T o){
    // devuelve -1 en el caso que se considera this antes que o
    // devuelve 0 en el caso qque this tiene el mismo orden que o
    // devuelve 1 en el caso que se considera this despues que o
}

A simple implementation for example Integer leg would be:

public int compareTo(int i){
    return Integer.signum(this - i));
}

The implementation in your case seems strange to me.

 if(e.getAtributo() % getAtributo() == 0)

this code returns true if e.getAtributo () divided by getAtributo () has no module, it means in the case that e.getAtributo () is multiple integer of getAtributo (). The implementation of compareTo returns 1 in this case, implying that this would be greater than e in the sequence. It does not make much sense like that.

    
answered by 09.01.2017 в 23:50