0

I am trying to make an implementation of a Binary Tree for a Words each of a which have a pattern (ex hello - pattern is ABCCD)

I keep getting a null pointer exception on the line it states

    while(pos.getPattern() != null || a){

I dont understand why- there are checks in place. Also when I print pos.getPattern() - I get a string not a null value

I could really use some help

public void AddWord(String word) {
    TreeNode pos = root;
    boolean a = true;
    String pat = PatternMaker.MakePattern(word);
    while(pos.getPattern() != null || a){

        if (pos.getPattern().equals(pat)) {
            WordList list = pos.getList();
            list.insertWord(word);
            pos.setList(list);
            a = true;
        } else if (pat.compareTo(pos.getPattern()) > 0) {
            pos = pos.getRight();
        } else {
            pos= pos.getLeft();

        }
    }
    if(pos ==null){
        pos = new TreeNode(word, pat);
    }
}
Anonymous Dodo
  • 261
  • 3
  • 17

3 Answers3

2

You need to add null check for pos in your while loop.

At some point pos is going to become null inside your while loop.

public void AddWord(String word) {
    TreeNode pos = root;
    boolean a = true;
    String pat = PatternMaker.MakePattern(word);
    while((pos!=null && pos.getPattern() != null) || a){

        if (pos.getPattern().equals(pat)) {
            WordList list = pos.getList();
            list.insertWord(word);
            pos.setList(list);
            a = true;
        } else if (pat.compareTo(pos.getPattern()) > 0) {
            pos = pos.getRight();
        } else {
            pos= pos.getLeft();

        }
    }
    if(pos ==null){
        pos = new TreeNode(word, pat);
    }
}

Hope this helps!

anacron
  • 6,443
  • 2
  • 26
  • 31
  • I am guessing the original poster meant to include the "if(pos == null)" conditional inside his while loop. That would have prevented the NPE, and it seems pointless where it is. There would seem to be little point to reinitializing a null reference immediately before exiting the method. But it is also possible that there was other code that was omitted. – Teto Mar 03 '17 at 06:22
0

You code has a line like pos = pos.getLeft(). If that method returns null then calling pos.getPattern() will throw NPE.

Teto
  • 475
  • 2
  • 10
0

The null value checks if the node of the tree is empty or not. You can denote any value to denote the empty node but it should not overlap with values of the string. You can use Empty String "" to denote empty values if your collection has to be of type String in some other language. It is recommended to leave the value as null as it avoids initialization cost and makes the checking run faster.

As @Teto explained the getPattern will throw the Null Pointer on Empty String.

devssh
  • 1,184
  • 12
  • 28