【问题标题】:inserting into a doubly linked list (getting null pointer exception) java插入双向链表(获取空指针异常)java
【发布时间】:2015-06-21 23:32:23
【问题描述】:
My code is as follows:

//Node class (inner class)
    private class Node
    {
        private String command;
        private String fileName;
        private int fileSize;
        private Node next;
        private Node prev;

        //constructor of Node
        private Node(String command, String fileName, int fileSize, Node prev, Node next)
        {
            this.command = command;
            this.fileName = fileName;
            this.fileSize = fileSize;
            this.prev = prev;
            this.next = next;
        }
    }

    private Node head;
    private Node tail;
    int size;

    //constructor of list
    public ReadInput()
    {
        diskSize = 0;
        head = null;
        tail = null;
        size = 0;
    }

    public void insert(String command, String fileName, int fileSize)
    {

          if (head == null)
            { 
                head = tail = new Node(command, fileName, fileSize, null, null );
                size ++;
            }

          else 
            {
                for(Node temp = head; temp != null; temp = temp.next)
                {

                        temp.next = new Node(command, fileName, fileSize, temp, temp.next.next);
                        temp.next.next.prev = temp.next;
                        size++;
                        if ( fileName == temp.fileName)
                             System.out.println("ID already exists!");
                        break;

                }
            }       
    }

我只是想插入我的双向链表。我有另一种方法,它使用正确的参数调用插入以添加到我没有在此处发布的链接列表,因为它是不必要的。第一次插入头部很好,但在第二次插入时,在调试我的程序时,我发现我在行 temp.next = new Node(command, fileName, fileSize, temp, temp.next.next); 上得到一个空指针异常 我看不到哪里出错了,谁能帮忙?谢谢

【问题讨论】:

  • 我知道什么是空指针异常……但这并不意味着我总能解决它!
  • 你看“如何解决”部分了吗?你的 for 循环说“temp 不是 null,所以 temp = temp.next (可以将 temp 设置为 null)。
  • 第一次进入循环的 else 部分时,这不应该发生,因为 temp = head。但我的程序第一次执行 else 部分时出现错误。

标签: java doubly-linked-list


【解决方案1】:

对于您插入的第一个元素,从一个空列表开始,因此它通过 if 块

      head = tail = new Node(command, fileName, fileSize, null, null );

所以 head.next = null

当你插入第二个元素时,代码跳转到 else 块

       temp.next = new Node(command, fileName, fileSize, temp, temp.next.next);

如果是第二个项目,

温度 = 头

temp.next =null

temp.next.next => 空引用异常(最后一个参数传递给构造函数)

此外,查看您的代码,您似乎不想将 temp.next.next 传递给您想要传递 temp.next 的构造函数。将该语句更改为

     temp.next = new Node(command, fileName, fileSize, temp, temp.next);

【讨论】:

  • 但是为什么我不能将空值传递给构造函数?
  • 你可以传递一个空值。 temp.next 为空。但是当您尝试访问 temp.next.next 时,您实际上是在尝试访问 null 的下一个属性,因此是 NRE。
猜你喜欢
  • 1970-01-01
  • 2016-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多