-2

I have a doubleLinkedList and need to implement a recursive toString() method without parameters. Here is what I have, and it throws a NullPointerException

//Print forwards
public String recursiveToString(){
  return first.rTS();
}

//Print backwards
public String recursiveBackwardsString(){
  return last.rBS();
}


    //Recursive helper in the node class
    public String rBS(){
      if (this!=null)
        return info+" "+back.rBS();
      return "";
    }

    //Recursive helper in the node class
    public String rTS(){
      if (this!=null)
        return info+" "+next.rTS();
      return "";
    }

1 Answers1

1

this won't be null in any code, if some method in null is called, the NullPointerException is thrown before the body of method is reached, so, the protection from null here is incorrect:

if (this != null)
    return ...

You should write it in this way:

public String rBS(){
    if (back != null)
        return info+" "+back.rBS();
    return info;
}

and the same thing for rTS.

Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48