Check if the object is null

I have a linked list in which the first node contains a null object. means that firstNode.data is null, firstNode.nextPointer = null, firstNode.previousPointer = null.

And I want to check if firstNode is null or not. So I tried -

if(list.firstNode == null){ //do stuff } 

but it doesn’t work?

I also tried an equal. Any suggestions?

I tried to print. And I got like -

{null} - firstNode

+6
source share
6 answers

I think your firstNode not null , but its fields. Try something like this:

 if (list.firstNode.data == null) { //do stuff } 
+13
source

You tried

 if (list.firstNode.data == null) { /* Do stuff */ } 
+1
source

You verify that list.firstNode is null. Do you want to check

 list.firstNode.data==null 
0
source

The answer to the question. You said:

  have a linked list in which first node contains null object. **means firstNode.data is equal to null**, 

This means that you must do the following:

 if(list.firstNode.data == null){ //do stuff } 
0
source

It seems to me that your question is related to processing a doubly linked list.
To check if it is used empty: (list.firstNode.next == list.firstNode.previous) this is true for an empty doubly linked list.

0
source

You can check if all node fields are empty:

 Node firstNode = list.firstNode; if(firstNode.data == null && firstNode.nextPointer == null && firstNode.previousPointer == null) { //Do stuff } 

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)) { //Do stuff } 
0
source

Source: https://habr.com/ru/post/908847/


All Articles