Java while循环代码中的null指针异常
我清除了自由块Java while循环代码中的null指针异常,java,nullpointerexception,Java,Nullpointerexception,我清除了自由块 private DoublyLinkedList freeblock = new DoublyLinkedList(); 我在构造函数中初始化freeblock freeblock.add(new DoublyLinkedList.Node(null, null, 0, initBlockSize)); 在我班的一个方法里面,(下面是我方法的一部分。) 我得到空指针异常。我认为while循环有问题。有人能帮我解决这个问题吗 症状:java.lang.NullPointerEx
private DoublyLinkedList freeblock = new DoublyLinkedList();
我在构造函数中初始化freeblock
freeblock.add(new DoublyLinkedList.Node(null, null, 0, initBlockSize));
在我班的一个方法里面,(下面是我方法的一部分。)
我得到空指针异常。我认为while循环有问题。有人能帮我解决这个问题吗
症状:java.lang.NullPointerException
放大(linearempool.java:220)
显然,
freeblock.head
为空。看看add
做了什么。你的放大
方法似乎有点危险。尝试将null
检查更改为:
private void enlarge(int addSize) {
DoublyLinkedList.Node node = freeblock.head;
while (node != null) {
node = node.next;
}
}
至于您的
head
为null
的原因,我将调试freeblock.add(…)
方法。首先检查freeblock.head是否为null,因为它很可能是:
if(node!=null){
while(node.next!=null){
....
}
else{
System.out.println("Freeblock is null but why.....");
}
如果freeblock.head可以为null,您可能应该正常执行此操作。只是为了清理:
void newMethod(Node node, int size){
if(node!=null)
enlarge(size);
else{
System.out.println("Freeblock is null");
}
}这是一个学习如何调试的好机会。如果您仍然需要帮助,最好发布一个自包含的可编译示例。此外,我们应该知道双链接列表是关于什么的。您是否有API文档可供参考?这个例子应该匹配编译器输出,这样我们就可以看到代码中第220行的实际位置。这里唯一可能抛出nullpointerexception的是“node.next!=null”行,因为节点变量本身可以为null。第220行是什么?你喜欢system.out.println(freeblock.head)吗要查看它是否为null?我建议简化它,然后
DoublyLinkedList.Node=null
@talexDoublyLinkedList.Node=freeblock.head代码>很好。OP需要一个开始的节点
。我的意思是,作为代码的结果,您得到节点==null
。原始代码获取的节点等于列表中的最后一个节点。
void newMethod(Node node, int size){
if(node!=null)
enlarge(size);
else{
System.out.println("Freeblock is null");
}