在Java中实现CompareTo

时间:2017-11-07 05:04:31

标签: java comparable

我有一个班级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
}

现在

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 */
    }
}

我想在删除一个元素后按此顺序显示我的队列,如果我删除一个位置为1的元素,那么其余部分必须如下所示:2,3,4,5如果我删除另一个它有出现:3,4,5等等。我试过&#34; Integer.compare(this.position, other.position);&#34; 并且是一样的

2 个答案:

答案 0 :(得分:0)

没有足够的信息可以确定,但我猜你正在使用Iterator方法返回的PriorityQueue.iterator()来验证队列的排序。

现在,该方法的JavaDoc明确指出(强调我的):

  

返回此队列中元素的迭代器。迭代器可以   不按任何特定顺序返回元素

答案 1 :(得分:0)

要使用java.util.PriorityQueue,您的类需要在创建Comparable的实例时实施Comparator或指定PriorityQueue。队列中的元素将从低值到高值排序,元素将通过Comparator.compareComparable.compareTo方法进行评估。

在您的情况下,您的班级Person实施Comparable<Person>,您必须确定Person的顺序。此实现将使元素按position

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

当您使用PriorityQueue.poll()时,它会为您提供最小值元素。

注意java.util.PriorityQueue及其迭代器实现CollectionIterator接口的所有可选方法。方法Iterator中提供的iterator()无法保证以任何特定顺序遍历优先级队列的元素。如果您需要有序遍历,请考虑使用Arrays.sort(pq.toArray())(来自Java doc)