如何将比较器传递给类的构造函数

时间:2014-11-17 07:28:36

标签: java constructor comparator

一个类有以下定义:

public class MinPQ<Key> implements Iterable<Key> {
private Key[] pq;                    // store items at indices 1 to N
private int N;                       // number of items on priority queue
private Comparator<Key> comparator;  // optional comparator

public MinPQ(int initCapacity) {
    pq = (Key[]) new Object[initCapacity + 1];
    N = 0;
}

public MinPQ() { this(1); }

public MinPQ(int initCapacity, Comparator<Key> comparator) {
    this.comparator = comparator;
    pq = (Key[]) new Object[initCapacity + 1];
    N = 0;
}

public MinPQ(Comparator<Key> comparator) { this(1, comparator); }
........
}

我想通过另一个类中的以下语句定义变量,但最后一行有错误。我想知道为什么以及如何定义它。谢谢!

class Searchnode {
    Board prebd;
    Board curbd;
    int moves;
}

class BoardComparator implements Comparator<Board> {
    public int compare(Board bd1, Board bd2) {
        if (bd1.manhattan() > bd2.manhattan())
            return 1;
        else if (bd1.manhattan() < bd2.manhattan())
            return -1;
        else
            return 0;
    }
}

private MinPQ<Searchnode> pq = new MinPQ<Searchnode>(new BoardComparator());

1 个答案:

答案 0 :(得分:1)

从偶然的一瞥看起来你的MinPQ看起来是MinPQ<Searchnode>而你的比较器是Comparator<Board>而你的班级被定义为

public class MinPQ<Key> implements Iterable<Key> 
{
    public MinPQ(Comparator<Key> comparator) { this(1, comparator); }
}

所以我希望你必须将comparator<SearchNode>传递给那个构造函数。