[Solved] Implement a CompareTo in Java [closed]


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)

1

solved Implement a CompareTo in Java [closed]