Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从链表中的索引中获取元素_Java_Linked List - Fatal编程技术网

Java 从链表中的索引中获取元素

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

我正在编写自己的LinkedList类(我知道API中有一个..等等),我的DLink中存储了整数,getElement()返回链接中存储的整数

我从“return temp.getElement();”行中得到一个空指针异常。我的get方法是否有问题?e、 为什么我需要这个方法:当我调用get(0)时,我想返回列表中的第一个元素

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


我建议您只需调试这段代码并查看在运行时定义的数据结构。

如果您遇到空指针异常,在这种情况下,有两种合理的解释

  • 您的列表是空的,也就是说没有firstLink可以开始,您得到一个空指针,因为您试图访问一个尚未初始化的指针

  • 您的列表只有一个元素。因此,firstLink.next()将为您提供一个空指针

  • 在进入遍历列表的while循环之前,应该始终执行一些检查

    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