为什么我们可以向java LinkedList添加null元素? [英] Why can we add null elements to a java LinkedList?

查看:3722
本文介绍了为什么我们可以向java LinkedList添加null元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用链接列表的java.util实现。我想知道为什么它允许我们添加null元素,我们甚至可以通过它们迭代?

I'm using java.util implementation of a linked list. I was wondering why it allows us to add null elements, and we can even iterate through them?

这不会打破链表的位置,我们有一个指向下一个元素的元素,如果我们添加了空元素并尝试迭代链接列表的常规实现将会破坏。

Doesn't that defeat the point of a linked list, where we have an element that points to the next element, and the conventional implementation of a linked list would break if we added null elements and tried to iterate over it.

推荐答案

查看Java 7源, LinkedList 被实现为一系列节点。

Looking at the Java 7 sources, LinkedList is implemented as a series of nodes.

private static class Node<E> {
    E item;
    Node<E> next;
    Node<E> prev;

    Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}

每个节点都有一个前一个节点和下一个节点的引用节点,以及项目。当您在列表中插入空值时,您将插入 $ 项目 null节点,但 next prev 指针是非空的。

Each node has a reference to the previous node and next node, as well as an item. When you insert a null value into the list, you're inserting a node with a null value for item, but the next and prev pointers are non-null.

这篇关于为什么我们可以向java LinkedList添加null元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆