I am new to tries and testing how it works. Right now I am building a contact list. I add 'Prashanth' and 'Pradep' to the trie and when I search 'Pra' I should receive the count as two. My approach is having the variable size in each node and returning it when the string of same length is found. There are some unnecessary things/variables like payload etc which I used for debugging. The problem I found is when I store a character and a node in hashmap, empty node is getting stored. So I am getting 0 as answer all the time.
public class tries {
public static class Node {
HashMap<Character, Node> children = new HashMap<>();
boolean endOfWord = false;
int size =0;
int payload = 10;
public void setNode(char c, Node n) {
children.put(c,n);
}
public Node getNode(char c) {
return children.get(c);
}
public void addNode( String s,int index) {
Node current = children.get(s.charAt(index));
size++;
if(index ==s.length()-1)
{
endOfWord = true;
return;
}
if(current== null)
{
current.payload = 11;
this.setNode(s.charAt(index),current);
}
addNode(s,index+1);
}
public int findcount(String s, int index) {
Node current = children.get(s.charAt(index));
if(index ==s.length()-1)
{
current.endOfWord = true;
return current.size;
}
if(current == null)
{
return 0;
}
return findcount(s,index+1);
}
}
public static void main(String args[])
{
String c1 = "Prashanth";
String c2= "Pradep";
Node n = new Node();
//tries t = new tries();
n.addNode(c1,0);
n.addNode(c2,0);
System.out.println(n.findcount("Pra",0));
}
}
Error which I get If i run this code. ( I will get 0 if I alter a bit)
Exception in thread "main" java.lang.NullPointerException
at tries$Node.addNode(tries.java:35)
at tries.main(tries.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)