首页 > 解决方案 > 如何从方法中完成并返回列表?

问题描述

我正在尝试在nearest方法中填写一个新列表。基本上,我做一个比较并添加符合 if case 的节点。我已经有一个填充了一些值的 LinkedList,我想将它们中的一些添加到一个名为 nearList 的新列表中并将其返回。

public RankList nearest (Point p,double maxDist){
        RankList nearList = new RankList();
        Node current = first;
        while (current != null) {
            System.out.print(current);
            if((current.getPoi().location.dist(p))<maxDist){//Finding the distance between the added points with p argument
                nearList.insert(record); //Insert the distances shorter than maxDist in a new list.
            }
            current = current.getNext();
        }
        System.out.println("null");
        return nearList;
    }

从 main 调用方法:

    public static void main(String[] args) {
RankList list1 = new RankList();
        list1.nearest(p,maxDist);
        list1.printList();
}

打印列表方法:

 public void printList() {
        Node current = first;
        System.out.print("HEAD -> ");
        while (current != null) {
            System.out.print(current);
            System.out.print(" -> ");
            current = current.getNext();
        }
        System.out.println("null");
    }

但似乎没有节点被添加到列表中,我很困惑为什么。

结果:

HEAD -> null

标签: javamethodslinked-list

解决方案


nearList.insert(record)

在整个代码段中都没有record提到该变量。据推测,它是您将此方法放入的任何类中的一个字段。三个问题:

  1. 该方法的设计似乎不适用于任何类的上下文;它通过参数获取操作所需的所有信息。它应该是静态的吗?那时,您的使用record会被标记为编译器错误(这优于“我不知道为什么这不起作用,我最好问一下”)。

  2. 以上听起来是错误的;听起来nearest应该是您发送到 RankList 的消息;它应该是 RankList 上的非静态方法,也许吧?很难说,粘贴没有包含足够的上下文。

  3. 当然,不要使用记录。我想你的意思是current


推荐阅读