a*******y 发帖数: 199 | 1 最近在学点java,遇到个问题想请教。
首先有一个类的定义如下:
public class MinPQ implements Iterable {
private Key[] pq; // store items at indices 1 to N
private int N; // number of items on priority
queue
private Comparator comparator; // optional comparator
/**
* Create an empty priority queue with the given initial capacity.
*/
public MinPQ(int initCapacity) {
pq = (Key[]) new Object[initCapacity + 1];
N = 0;
}
/**
* Create an empty priority queue.
*/
public MinPQ() { this(1); }
/**
* Create an empty priority queue with the given initial capacity,
* using the given comparator.
*/
public MinPQ(int initCapacity, Comparator comparator) {
this.comparator = comparator;
pq = (Key[]) new Object[initCapacity + 1];
N = 0;
}
/**
* Create an empty priority queue using the given comparator.
*/
public MinPQ(Comparator comparator) { this(1, comparator); }
我现在想在另一个类中用最后一个构造函数来定义一个变量,代码如下:
public class Solver {
private Searchnode lpsrchnode;
private Searchnode twin_lpsrchnode;
private boolean issolvable;
private int moves;
private int twin_moves;
class Searchnode {
Searchnode prenode;
Board bd;
int moves;
}
public static class SrcnodeComparator implements Comparator {
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 pq = new MinPQ(
new SrcnodeComparator());
private MinPQ twin_pq = new MinPQ(
new SrcnodeComparator());
但上述两个变量pq和twin_pq定义一直有错,不知道为什么。正确的写法又应该是怎么
样的呢?多谢啦! | z****e 发帖数: 54598 | | W***o 发帖数: 6519 | 3 my 2c: the problem is with your static comparator class, because eclipse
cannot see the return value - as it is buried in the if-else blocks. I would
suggest you put the last "return 0" as a default (outside the if-else) for
the comparator method.
public int compare(Board bd1, Board bd2) {
if (bd1.manhattan() > bd2.manhattan())
return 1;
else if (bd1.manhattan() < bd2.manhattan())
return -1;
return 0;
}
【在 a*******y 的大作中提到】 : 最近在学点java,遇到个问题想请教。 : 首先有一个类的定义如下: : public class MinPQ implements Iterable { : private Key[] pq; // store items at indices 1 to N : private int N; // number of items on priority : queue : private Comparator comparator; // optional comparator : /** : * Create an empty priority queue with the given initial capacity. : */
|
|