gpt4 book ai didi

java - 如何在自定义链表类中避免出现 NullPointerException?

转载 作者:行者123 更新时间:2023-12-01 17:47:30 24 4
gpt4 key购买 nike

我正在设计一个名为 unlinkNode 的非静态 void 方法,该方法采用 Node n 作为参数。它应该确保该节点与其之前和之后的节点解除链接。它需要改变n之后的节点的prev和n之前的节点的next。目前,当我运行它时,我收到错误

[ ERROR    ] exception in unit test code!
java.lang.
NullPointerException
at LinkedList.unlinkNode(LinkedList.java:111)
at UNITTEST.test_default(UNITTEST.java:19)
at UNITTEST.main(UNITTEST.java:81)

第 111 行是 n.getPrev().next = null;

即使我已经放入 if 语句来确保如果 n 是尾部,则不访问其上一个,如果是头部,则不访问其下一个,以确保没有空值正在访问。

方法如下:

public void unlinkNode(Node n) {
if(head != n && head != null) {
n.getNext().prev = null;
}
if (tail != n && tail != null) {
n.getPrev().next = null;
}
}

以及设置一切的代码

public class LinkedList {
public static class Node{
String key;
int value;
Node next;
Node prev;

public Node(String key, int value) {
this.key = key;
this.value = value;
}

public Node getNext() {
return next;
}

public Node getPrev() {
return prev;
}

public String getKey() {
return key;
}

public int getValue() {
return value;
}
}

private Node head;
private Node tail;

public LinkedList() {
head = null;
tail = null;
}

public Node getHead() {
return head;
}

public Node getTail() {
return tail;
}


public void addHead(String key, int val) {
Node n = new Node(key, val);

if(head == null) {
head = n;
tail = n;
} else {
head.prev = n;
n.next = head;
head = n;
}
}

public void addTail(String key, int val) {
Node n = new Node(key, val);

if(tail == null) {
head = n;
tail = n;
} else {
tail.next = n;
n.prev = tail;
tail = n;
}
}
}

最佳答案

看来您也为它们分配了空值,但检查尚未完成。我建议你抛出一个 NullPointerException 以便你能够自己处理它,例如在 try catch block 内。如果值是 null,这将为您准备好应对场景,然后执行此操作。

try {
// Your usual code here
} catch(NullPointerException e) {
// Do something if it hit an NPE
}

关于java - 如何在自定义链表类中避免出现 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60842506/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com