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;
}
}
}
我只是想插入到我的双重链接列表中。我有另一个方法,它用适当的参数调用insert来添加到链表中,我没有在这里发布,因为这是不必要的。头中的第一次插入很好,但在第二次插入时,在调试程序时,我发现temp.next = new Node(command, fileName, fileSize, temp, temp.next.next);
行出现了空指针异常我看不出哪里出了问题,有人能帮忙吗?感谢
对于插入的第一个元素,它以一个空列表开始,因此它会经过if块
head = tail = new Node(command, fileName, fileSize, null, null );
因此head.next=空
当您插入第二个元素时,代码跳转到其他块
temp.next = new Node(command, fileName, fileSize, temp, temp.next.next);
在第二项的情况下,
temp=头
temp.next=空
temp.next.next=>空引用异常(传递给构造函数的最后一个参数(
此外,查看您的代码,您似乎不想将temp.next.next传递给构造函数,而是希望传递temp.next。将该语句更改为
temp.next = new Node(command, fileName, fileSize, temp, temp.next);