Java 通过将null值与null值进行比较来检查null值时,在语句本身上获取null指针异常
我在代码中编写了一个条件,如果Object的值为null,它应该初始化一个新的对象,但是我在比较语句本身得到null指针异常。根据我的知识,我们可以比较两个空值 不知道我错过了什么。下面是我的代码Java 通过将null值与null值进行比较来检查null值时,在语句本身上获取null指针异常,java,nullpointerexception,Java,Nullpointerexception,我在代码中编写了一个条件,如果Object的值为null,它应该初始化一个新的对象,但是我在比较语句本身得到null指针异常。根据我的知识,我们可以比较两个空值 不知道我错过了什么。下面是我的代码 public class TrieNode { static final int Alphabet_Size = 26; class Tried { Tried children[] = new Tried[Alphabet_Size]; boolean isEndofWord; Tr
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]);
}
}
}
公共类三节点
{
静态最终整数字母表大小=26;
班级考试
{
试用儿童[]=新试用[字母表大小];
布尔isEndofWord;
试过
{
isEndofWord=假;
/*对于(int i=0;i如果note本身为null,则无法执行note。children[index]尝试类似if(note==null)的操作然后初始化对象您将获得一个NPE,因为您试图访问note
变量的子项
成员。note
被指定为指向根
。根据您的程序,根
从未被指定值,这意味着它在note
i时为空
指定给它的。注释变量本身必须为空