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.
解决方案
Looking at the Java 7 sources, LinkedList is implemented as a series of nodes.
private static class Node {
E item;
Node next;
Node prev;
Node(Node prev, E element, Node next) {
this.item = element;
this.next = next;
this.prev = 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.