嵌套的嵌套比较器类

时间:2017-08-13 22:34:14

标签: java comparator inner-classes

我很难将其编译,并且无法弄清楚原因。看起来我正在搞乱嵌套类。出于某种原因,ByManhattan类无法访问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

2 个答案:

答案 0 :(得分:3)

重命名参数名称:

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

不要将保留字this用于变量,这是编译错误。

答案 1 :(得分:1)

else if (0.26f < counter && counter <= 0.50f) 是保留字。这是编译错误的来源。在保留字之后命名任何参数/变量也是不好的做法,你应该将它命名为不同的东西。更改int _yellow.alpha=0; _orange.alpha=0; _red.alpha=0; if (counter <= 0.25f){ _yellow.alpha = 1; } else if (0.26f < counter && counter <= 0.50f){ //Where it should be stopping _orange.alpha = 1; }else { //Where it stops instead _red.alpha = 1; NSLog(@"counter= %f", counter); //This outprints 0.333333 }

的第一个参数