Java 将 Node 实现为泛型类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19128858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implementing Node as a generic class
提问by Iva
I recently started learning Java and the last thing I was going over was generic programming and now linked list. Now, I'm trying to implement the node class from linked lists as generic, but I was having some trouble. I'm trying to declare a toString
method that can iterate through this linked list and print its elements, however I keep getting a NullPointerException
every time I call link.toString()
and I'm confused on why I'm getting this error. I know that the format of my toString
method is not as efficient as it can be but I was trying to follow my book instructions. I'm presenting my Node
class and the applications one as well.
我最近开始学习 Java,最后一件事是泛型编程和链表。现在,我试图将链接列表中的节点类实现为泛型,但我遇到了一些麻烦。我正在尝试声明一个toString
可以遍历此链表并打印其元素的方法,但是NullPointerException
每次调用时我都会收到一个,link.toString()
并且我对为什么会收到此错误感到困惑。我知道我的toString
方法的格式并不像它所能达到的那样有效,但我试图按照我的书上的说明进行操作。我Node
也在介绍我的课程和应用程序。
public class GenericNode<E> {
private E data;
private GenericNode<E> link;
public GenericNode(E intialData, GenericNode<E> initialLink){
data=intialData;
link=initialLink;
}
public GenericNode<E> addNodeAfter( E element ) {
link = new GenericNode<E>( element, link );
return link;
}
public String toString(){
String field1=" ";
String field2=" ";
String result=" ";
if(data==null){
field1="dummy";
System.out.println("in dummy");
}
field1="Data: "+ data.toString()+ "\n";
if(link==null){
field2="null in tail!";
System.out.println("in tail");
}
field2="link: data: "+link.data.toString() ;
if(link!=null){
result=field1+field2+link.toString();
}
return field1+field2;
}
}
public class NodeAppilication {
public static void main(String[] args){
GenericNode<String> head=new GenericNode<String>("Paul", null);
GenericNode<String> tail=new GenericNode<String>("Saul",head.addNodeAfter("Saul"));
//figure 1
System.out.print(head.toString());
//figure2
tail.toString();
GenericNode<String> dummy=new GenericNode<String>(null,head);
}
}
回答by dasblinkenlight
Your checks for null
are missing an else
:
您的支票null
缺少一个else
:
if(data==null){
field1="dummy";
System.out.println("in dummy");
} else { // <<== Add an "else" here
field1="Data: "+ data.toString()+ "\n";
}
if(link==null){
field2="null in tail!";
System.out.println("in tail");
} else { // <<== And here...
field2="link: data: "+link.data.toString();
}
Currently, your code checks for null
, sets the value of field1
and field2
to the default, and then immediately tries to dereference a data
or a link
, causing a null pointer exception.
目前,您的代码检查null
,设定值field1
,并field2
为默认值,然后立即尝试取消引用data
或link
,导致空指针异常。