搜索链表时出现空指针异常

时间:2015-04-27 04:17:27

标签: java search nullpointerexception linked-list

我为链表创建了一个搜索方法。当我搜索列表中存在的内容时,它可以正常工作。如果我搜索不在列表中的内容,那么我会得到一个空指针异常。

我不知道如何才能获得此异常。

以下是方法:

 // these two search methods return the node containing the substring given
public UNode search(String cityName)
{
    return search(cityName,this);//line 90
}//end search()-------------------------------------------------------------
private UNode search(String cityName, UNode current)
{
    if(current != null)
    {
        if (current.getCity().getName().contains(cityName))
        {
            System.out.println("Node '" + current.getCity().getName() 
                    + "' has been found and returned.");
            return current;
        } else
        {

            return search(cityName,current.next);//line 105
        }
    }
    else
    {
        System.out.println("No node containing the substring '" 
                + cityName + "' can be found, returning null");
        return null;
    }
}//end search()-------------------------------------------------------------

据我所知,这是搜索不存在的东西时发生的情况:该方法继续使用current.next递归调用search(),它到达最后一个元素并调用search(cityName,null),然后current为null,表示未找到,返回null。

我在这里遗漏了什么吗?我究竟做错了什么?我应该抛出空指针异常吗?

以下是我调用搜索方法的方法:

public static void uNodeTest(City[] cities)
{


    UNode unvisited = new UNode();

    unvisited.addCities(cities);


    String a = unvisited.getNext().getNext().getNext().getCity().getName();

    System.out.println(a);

    UNode current = unvisited;
    while(current.getNext() != null)
    {
        System.out.println(current.getCity().getName());
        current = current.getNext();
    }
    UNode phil = unvisited.search("not a city");
}

堆栈追踪:

java.lang.NullPointerException
at cityproject.UNode.search(UNode.java:105)
.
.
.
at cityproject.UNode.search(UNode.java:105)//(omitting repeats)
at cityproject.UNode.search(UNode.java:90)
at cityproject.CityProject.uNodeTest(CityProject.java:104)
at cityproject.CityProject.main(CityProject.java:79)

1 个答案:

答案 0 :(得分:0)

我会在调用递归搜索之前添加一个检查,以查看current.next是否为null:

if(current.next != null) {
    return search(cityName,current.next);
}
else {
    return null;
}

这可能会解决空指针异常......

相关问题