首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嵌套的比较器类

嵌套的比较器类
EN

Stack Overflow用户
提问于 2017-08-14 06:34:14
回答 2查看 192关注 0票数 1

我很难编译这段代码,也不太明白为什么。看起来我把嵌套的类搞乱了。由于某种原因,ByManhattan类不能访问Node?如果有人能解释这是为什么,以及错误消息的含义,并提供建议,这将是有帮助的。谢谢。

代码语言:javascript
复制
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) {
 .
 .
 .

我得到的错误是:

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-14 06:45:22

重命名参数名称:

代码语言:javascript
复制
   public int compare(Node n1, Node n2) { // this is line 37
        return n1.manhattan- n2.manhattan;
    }

不要为变量使用保留字this,这是一个编译错误。

票数 3
EN

Stack Overflow用户

发布于 2017-08-14 06:48:03

this是保留字。这就是编译错误的来源。在保留字之后命名任何参数/变量也是不好的做法,您应该给它命名不同的名称。更改int compare(Node,Node)的第一个参数

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45665461

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档