You can check if all node fields are empty:
Node firstNode = list.firstNode; if(firstNode.data == null && firstNode.nextPointer == null && firstNode.previousPointer == null) {
To prevent code from repeating, you can either create an isNull () instance method to run the test, or create a NULL object and override the equals method in the node class to check if the node is null node as you described.
class Node<E> { //The null node, assuming your constructor takes all three values. public static final Node NULL = new Node(null, null, null); //Fields here with constructors etc. @Override public void equals(Object obj) { if(!obj instanceof Node) return false; Node<?> node = (Node<?>)obj; if(node.data.equals(this.data) && node.nextPointer == this.nextPointer && node.previousPointer == this.previousPointer) { return true; } else { return false; } }
Then, when you want to check if node is null:
if(list.firstNode.equals(Node.NULL)) {
Hedja source share