-1
public class Node {

  int value;
  List<Node> childNodes;

  Node(int x) {
    value = x;
  }
}

Above is the definition of the tree node and we have a tree.

Node root = new Node(0);
Node n1 = new Node(1);
root.childNodes.add(n1);  Line 1

This is how I construct the initial tree structure in main, however, I got a nunllpointerexception in line 1. Anybody knows the reason?

nano_nano
  • 12,351
  • 8
  • 55
  • 83
sevenxuguang
  • 177
  • 9
  • I don't think that it is duplicate, it is in a specific condition. – sevenxuguang Dec 21 '15 at 14:33
  • when you declare `List childNodes;` as a property, you do not initialize the generic List (the list is a generic interface, not a class; it's null as long as you do not initialize it). E.g. if you add into your constructor `childnodes = new ArrayList<>();` or if you declare the property as `List childNodes = new Arraylist<>();`, it won't throw an exception. – LowLevel Dec 21 '15 at 14:38
  • 1
    @sevenxuguang The duplicate explains how to solve NPE in general - if you try to understand how it you will find that fixing your problem is easy... – assylias Dec 21 '15 at 14:42
  • Ok..................But I cannot delete the post and why my points get deducted so much...................... – sevenxuguang Dec 21 '15 at 14:44

1 Answers1

-1

where is childNodes initiated?

root.childNodes.add(n1);  Line 1

must throw a NPE.

add this in your Node class and it will work:

List<Node> childNodes = new ArrayList<>();

or

Node root = new Node(0);
Node n1 = new Node(1);
root.childNodes = new ArrayList();
root.childNodes.add(n1);
nano_nano
  • 12,351
  • 8
  • 55
  • 83
  • Sure, it says that "You can accept that in 10 minutes". – sevenxuguang Dec 21 '15 at 14:34
  • 1
    why the downvote? because I have answered a duplicate? – nano_nano Dec 21 '15 at 14:55
  • 2
    @StefanBeike Yes, probably. This is such an obvious duplicate - posting an answer to a question like this is often seen as reputation-grab, which someone decided was worthy for a downvote. On a sidenote, there's no need to get all huffy about it - it's one downvote, you've got plenty of rep to spare. – Mage Xy Dec 21 '15 at 14:55
  • not from my point of view. Closing something because it is a duplicate is ok for me. Downvoting a correct answer because of that is not ok. – nano_nano Dec 21 '15 at 14:57
  • 1
    Users are free to up- or downvote using any criteria they choose. The ideal is that they base their vote on the content of the answer; the reality is sometimes votes happen for other reasons. – Mage Xy Dec 21 '15 at 15:05
  • sure but a lot of answers I saw today were duplicates. nevertheless no reason for downvote. Our opinions are divided. Thats ok... – nano_nano Dec 21 '15 at 15:08