Java 从链表中的索引中获取元素
我正在编写自己的LinkedList类(我知道API中有一个..等等),我的DLink中存储了整数,getElement()返回链接中存储的整数 我从“return temp.getElement();”行中得到一个空指针异常。我的get方法是否有问题?e、 为什么我需要这个方法:当我调用get(0)时,我想返回列表中的第一个元素Java 从链表中的索引中获取元素,java,linked-list,Java,Linked List,我正在编写自己的LinkedList类(我知道API中有一个..等等),我的DLink中存储了整数,getElement()返回链接中存储的整数 我从“return temp.getElement();”行中得到一个空指针异常。我的get方法是否有问题?e、 为什么我需要这个方法:当我调用get(0)时,我想返回列表中的第一个元素 public int get(int index) { //forces the index to be valid assert (in
public int get(int index)
{
//forces the index to be valid
assert (index >= 0 && index < size());
DLink temp = _firstLink; //start at the head of the list
//iterate to the correct node
for(int i = 0; i < index; i++)
{
temp = temp._next;
}
return temp.getElement(); //and return the corresponding element
}
你什么时候初始化你的列表?或者更具体地说,
\u firstLink
在哪里声明和分配?
在获取空指针异常之前,您正在进行什么调用
没有看到上下文-我猜您没有正确初始化\u firstLink
我建议您只需调试这段代码并查看在运行时定义的数据结构。如果您遇到空指针异常,在这种情况下,有两种合理的解释
if(firstLink == null)
return;
if(firstLink.next() == null)
return;
或者在while循环之前有一个初始子句
if(firstLink != null && firstLink.next() != null)
while(true)
...do-something
输入是什么?如果您的列表为空,那么temp将为null…如果您尚未创建列表。在我看来,
\u firstLink
在调用get(0)
时是空的。您在哪里将其设置为非空值?
if(firstLink != null && firstLink.next() != null)
while(true)
...do-something