Search code examples
javacomparable

Implement a CompareTo in Java


I have an class PersonQ

public class PersonQ {
    Queue <Person> queue;
    int Rows;

    public PersonQ(int r){
        queue = new PriorityQueue<Person>(); 
        Rows = r; 
    }

    //Also I have getters and setters and a method to fill randomly with Random
}

And now

public class Person implements Comparable <Person> {
    String name; 
    int id; 
    double salary; 
    int position;

    public Person(String pN, int pID, double pSal, int pPos) {
        this.name = pN; 
        this.id = pID; 
        this.salary= pSal; 
        position=pPos;
    }

//Also I have getters and setters 

    @Override
    public int compareTo(Person other) {
        /*There I don't know how to make my statements because at the moment when I remove an element 
        it sorts wrong; Look, when I add 5 elements randomly it gets its proper position: 1, 2, 3, 4 
        and the last 5 when I use the method poll() it removes the element with position 1 but the 
        next step is that it sorts in a weird way, for example sometimes it starts with the element 
        with position 5, 4, 2 or 3 it occurs randomly and I want to see it in their proper order by its position */
    }
}

I want to show my Queue in this order after remove an element, If I remove an element with position 1, then the rest of them must appear like this: 2,3,4,5 and if I remove another it has to appear: 3,4,5 and so on. I tried with "Integer.compare(this.position, other.position);" And is the same


Solution

  • To use java.util.PriorityQueue, your class need to implement Comparable or specify Comparator when create an instance of PriorityQueue. The elements in queue will be sorted from low value to high value, the element will be evaluated by Comparator.compare or Comparable.compareTo method.

    In your case, your class Person implements Comparable<Person>, you have to determine the order of Person. This implementation will make the elements order by position:

    @Override
    public int compareTo(Person other) {
        return position - other.position;
    }
    

    When you use PriorityQueue.poll(), it will give you the least value element.

    Note: java.util.PriorityQueue and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()) (From Java doc)