Java NullPointerException for null condition check
•
Java
I have a very basic method as part of the binary search tree. If the current binary node has a correct child node, it only returns true. If the child node on the right points to null, it returns false
public boolean hasRight(){ if(right.element != null){ return true; }else{ return false; }
But whenever I test this code, I know that I will reach a node without the correct child node, and I want my code to only return false, then Java will throw a NullPointerException at this line
if(right.element != null)
Instead of returning false as I expected
Edit:
Fixed my code, just check if you are null before trying to get the correct element
public boolean hasRight(){ if(right != null){ return true; }else{ return false; } }
Solution
The right itself is empty Check it before attempting to access it
if (right != null && right.element != null){
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码