嵌套嵌套比较器 类

Nested Nested Comparator Classes

我很难编译它,也不太明白为什么。看起来我在用嵌套的 classes 搞砸了。出于某种原因,ByManhattan class 无法访问 Node?如果有人可以解释为什么会这样以及错误消息的含义并提供建议,那将很有帮助。谢谢

public class Solver {

  private class Node implements Comparable<Node>{
    private Board board;
    private Node previous;
    private int moves;
    private int manhattan;
    private int priority;

    Node(Board b, Node p) {
        board = b;
        previous = p;
        if (previous == null)
            moves = 0;
        else
            moves = previous.moves + 1;
        manhattan = board.manhattan();
        priority = moves + manhattan;
    }

    public int compareTo(Node that) {
        return this.priority - that.priority;
    }

    // Why Doesn't this work???
    public Comparator<Node> manhattanOrder() {
        Comparator<Node> m = new ByManhattan();
        return m;
    }

    private class ByManhattan implements Comparator<Node> {
        public int compare(Node this, Node that) { // this is line 37
            return this.manhattan- that.manhattan;
        }
    }
  }

 MinPQ<Node> pq;
 ArrayList<Node> solution;

 // find a solution to the initial board (using the A* algorithm)
 public Solver(Board initial) {
 .
 .
 .

我得到的错误是:

Solver.java:37: error: the receiver type does not match the enclosing class type
public int compare(Node this, Node that) {
                   ^
required: Solver.Node.ByManhattan
found: Solver.Node

重命名您的参数名称:

   public int compare(Node n1, Node n2) { // this is line 37
        return n1.manhattan- n2.manhattan;
    }

不要对变量使用保留字this,那是编译错误。

this 是保留字。那是你编译错误的根源。在保留字之后命名任何 parameter/variable 也是不好的做法,您应该将其命名为其他名称。更改 int compare(Node,Node)

的第一个参数