Search code examples
javanullnullpointerexceptioncomparable

Java: checking if Comparable is not null returns NullPointerException


I have a big problem with this code and I have no idea how to cause it:

while(tree.find(indexreg)!=null){
        //do stuff
    }

For some reason, comparing tree.find(indexreg) with null causes a NullPointerException. Since this is a college project I have to use my own binary tree implementation instead of the one provided by Java. tree is a BinarySearchTree and indexreg is a Comparable object, that was already initialized. This is the code for find in the BinarySearchTree class:

public Comparable find(Comparable x) {
        return elementAt(find(x, root));
    }

It looks for the object in the tree and it returns null if it doesn't find it (I don't think you can return an empty Comparable object). I tried Googling but I didn't find an useful answer. Does anyone know how to make this code work?


Solution

  • I don't think the problem has anything to do with your Comparable.

    If the line while(tree.find(indexreg) != null) { throws a NullPointerException, it must be because tree is null. No other possibilities are credible.

    • Comparison of an object reference with null using == or != will NOT throw an NPE. So even if tree.find(...) returned a null, that can't be the cause of this exception.

    • Passing a null value as a method argument will NOT throw an NPE. So if indexreg was null, that wouldn't cause this exception. (An NPE could be thrown by the find method or something it calls, but the stacktrace will not show a different line in a different method as the origin of the exception.)


    (I could be misinterpreting the question. I'm assuming that the OP means "throws" when he says that the line "causes" the exception.

    Unfortunately, the OP is only posting snippets of code and hasn't shown us the stacktrace ... which is the critical piece of evidence.)