AKIWEB
AKIWEB

Reputation: 19612

check if an object is null

I have a linked list in which first node contains null object. means firstNode.data is equal to 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 this doesn't works?

I also tried equals too. Any suggestions?

I tried printing. And I got as-

{null} -- firstNode

Upvotes: 6

Views: 63220

Answers (6)

Skip Head
Skip Head

Reputation: 7760

Did you try

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

Upvotes: 1

user620244
user620244

Reputation:

You can check if all the fields of the node are null:

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

Or to prevent code repetition, you can either create an instance method isNull() to do the test or create a NULL object and override the equals method in your Node class to check if a node is equal to the 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 a node is null you can do:

if(list.firstNode.equals(Node.NULL)) {
    //Do stuff
}

Upvotes: 0

Cratylus
Cratylus

Reputation: 54074

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

Upvotes: 0

GETah
GETah

Reputation: 21409

The answer is in the question. You said:

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

This means you should do the following instead:

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

Upvotes: 0

Bohemian
Bohemian

Reputation: 424953

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

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

Upvotes: 13

David Nehme
David Nehme

Reputation: 21572

You checking for list.firstNode being null. Do you mean to check for

list.firstNode.data==null

Upvotes: 0

Related Questions