为什么我们可以向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.