• Post Reply Bookmark Topic Watch Topic
  • New Topic

Testing for 'null', without producing a NullPointerException error message  RSS feed

 
Jeremy Watts
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have written a method, that is occasionally passed a null object that I want to test for, and so 'filter out'. However, despite the "if Object == null" style of code, I get a NullPointerException error message at that same line, that I don't want, everytime I run the code.

My actual code is :-

if (parent.getChildren() != null)
{
do something
}

Here, 'parent' is an object of class 'TreeNode' (a class I have written), and 'parent.getChildren()' returns an object of type ArrayList<TreeNode>, which is just a list of TreeNode's. As, you may have guessed, I'm modelling a 'tree' data structure, which is a network of 'nodes', with connecting 'links', where each node has a parent node, as well as 'children' nodes too'.

When a node is instantiated, then initially it's parent node is set to null, and its list of child nodes is created as :- ArrayList<TreeNode> children = new ArrayList<TreeNode>(); , but then within the
constructor itself, I have set 'this.children = null'

Now, back to my point. How do I test for 'nullness' here, be able to handle it, without producing a NullReferenceException error?

Thanks
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
are you sure parent is not null? or rather...what exactly do you think you are testing for 'null-ness' here?

says "call the getChildren method on the object parent points to. However, if parent itself is null, you'll get the NPE. You may need to just do this:

or possibly even this:
 
Jeremy Watts
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yeah, of course that is it... how dull of me :S thanks
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!