[ACCEPTED]-check if an object is null-java

Accepted answer
Score: 13

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

if (list.firstNode.data == null) {
    //do stuff          
Score: 1

Did you try

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


Score: 0

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

Score: 0

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 1 means you should do the following instead:

if(list.firstNode.data == null){
     //do stuff          
Score: 0

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

Score: 0

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

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

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

    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 2 want to check if a node is null you can 1 do:

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

More Related questions