I have written a condition in code where if the value of Object is null, it should initialize a new object, but I am getting null pointer exception at the comparison statement itself. as per my knowlwdge we van compare two null values.
Not sure what a I missing. Below is my code
public class TrieNode
{
static final int Alphabet_Size = 26;
class Tried
{
Tried children[] = new Tried[Alphabet_Size];
boolean isEndofWord;
Tried()
{
isEndofWord = false;
/*for(int i=0; i<Alphabet_Size; i++)
children[i] = null; */
}
};
static Tried root;
public void insert(String key)
{
Tried note = root;
int index;
int itr;
for(itr=0; itr<key.length(); itr++)
{
index = key.charAt(itr)-'a';
if(note.children[index]==null) // Getting Null pointer Exception here
{
note.children[index] = new Tried();
}
note = note.children[index];
}
note.isEndofWord = true;
}
public boolean search(String key)
{
Tried note = root;
int index;
int itr;
for(itr=0; itr<key.length(); itr++)
{
index = key.charAt(itr)-'a';
if(note.children[index]==null)
return false;
note = note.children[index];
}
return (note!=null && note.isEndofWord);
}
public static void main(String[] args)
{
TrieNode tr = new TrieNode();
String keys[] = {"the", "their", "Aakash", "Aayush"};
for(int i=0; i<keys.length; i++)
{
tr.insert(keys[i]);
}
}
}
I Have tried adding null values for all the indexes in array(see the commented part of code) but even that is not helping