我创建了一个链接列表的搜索方法。当我搜索列表中确实存在的内容时,它可以正常工作。如果我搜索列表中没有的内容,则会出现空指针异常。
我不明白如何可能获得此异常。
方法如下:
// 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)
最佳答案
我会在调用递归搜索之前添加一个检查以查看 current.next 是否为 null:
if(current.next != null) {
return search(cityName,current.next);
}
else {
return null;
}
这可能会解决空指针异常...
关于java - 搜索链表时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29887127/