繁体   English   中英

如何在我的自定义链表类中避免此 NullPointerException?

[英]How do I avoid this NullPointerException in my custom linked list class?

我正在设计一个名为 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语句来确保 if n 是尾部,不访问它的上一个,如果它的头,不访问它的下一个,以确保没有访问 null 。

这是方法:

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;
        }
    }
}

我怀疑“getPrev”返回空值。 确认这一点的代码很少。 您无法查看是否调用了“addHead”或“addTail”。

仔细思考逻辑。 或者为自己画一幅画。

if(head != n && head != null) {
    n.getNext().prev = null;
}

假设nextprevheadtail都有其直观的含义,那么测试head != n并不意味着n会有next 这意味着n将有一个prev

另外……当您从列表中删除一个节点时, head怎么可能为null 那场只会是null ,如果该列表是空的,你将不会被去除空单什么。

所以上面应该是:

if (head != n) {
    n.getPrev().next = null;
}

并将相同的想法应用到下一个测试中。

(注意:我无法测试它。如果我建议的修复是错误的,请为自己找出应该是什么。像我一样,从第一原则开始。)

您似乎也为它们分配了空值,但检查未完成。 我建议您抛出一个 NullPointerException 以便您能够自己处理它,例如在 try catch 块中。 如果值为空,这将为您做好准备,然后改为执行此操作。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM