我正在尝试创建一个实现修改后的Set接口的LinkedSet对象类。当我尝试检查firstNode是否指向null时,我得到一个NullPointerException。我不确定如何解决这个问题。
以下是相关代码。
整体Set对象的构造函数
public class LinkedSet<T> implements Set<T> {
private Node firstNode;
public LinkedSet() {
firstNode = null;
} // end Constructor
阻碍我的方法
public int getSize() {
int size = 1;
Node current = firstNode;
while ((current.next) != null) {
size++;
current = current.next;
}
return size;
} // end getSize()
isEmpty()方法
public boolean isEmpty() {
Node next = firstNode.next; //Get error here
if (next.equals(null)) {
return true;
}
return false;
} // end isEmpty()
这是Node对象的私有内部类
private class Node {
private T data;
private Node next; //Get Error here
private Node(T data, Node next) {
this.data = data;
this.next = next;
} // end Node constructor
private Node(T data) {
this(data, null);
}// end Node constructor
} // end Node inner Class
最后这是主要的测试方法。
public class SetTester {
public static void main(String[] args) {
LinkedSet<String> set = new LinkedSet<String>();
System.out.println(set.getSize()); //Get error here
}
}
答案 0 :(得分:4)
如果没有节点,您的设置为空。因此,isEmpty()
实施是您的问题所在,因为即使您在构造函数中明确将其设置为firstNode
,它也会假设您始终拥有null
。
试试这个:
public boolean isEmpty() {
return firstNode == null;
}
编辑完第一个问题后编辑:
您仍然可以访问null(导致NullPointerException
),因为您将current
设置为firstNode
,而[root@localhost mysql-cluster]# ndb_mgmd -f /var/lib/mysql-cluster/config.ini
**-bash: ndb_mgmd: command not found**
又从未设置为空值。
答案 1 :(得分:2)
public boolean isEmpty() {
Node next = firstNode.next; //Get error here
if (next.equals(null)) {
return true;
}
return false;
} // end isEmpty()
这行给你NullPointerException,我希望:
Node next = firstNode.next; //Get error here
因为firstNode
可能是null
而且到目前为止没有指向任何地方。处理NullPointerException
也是最佳做法。所以,你应该做的是:
public boolean isEmpty() {
if (firstNode == null) { return true;}
return false;
} // end isEmpty()
另外,不要将null检查为:
next.equals(null)
始终将其检查为:
null == next
或next == null
答案 2 :(得分:1)
您需要检查firstNode
是否为null
,然后才会尝试在错误的行中访问它,因为您使用null
初始化它。
答案 3 :(得分:0)
在
public class LinkedSet<T> implements Set<T> {
private Node firstNode;
public LinkedSet() {
firstNode = null;
} // end Constructor
firstNode
为空,您没有将内存初始化到节点并在之后访问它。这就是您获取空指针异常的原因,因为您正在访问null。将其更改为。
public class LinkedSet<T> implements Set<T> {
private Node firstNode;
public LinkedSet() {
firstNode = new Node();
} // end Constructor
检查是否为空
public boolean isEmpty() {
return firstNode==null;
} // end isEmpty()
节点类
private class Node {
private T data;
private Node next; //Get Error here
private Node(T data, Node next) {
next= new Node();
this.data = data;
this.next = next;
} // end Node constructor
private Node(T data) {
this(data, null);
}// end Node constructor
} // end Node inner Class
主要
public class SetTester {
public static void main(String[] args) {
LinkedSet<String> set = new LinkedSet<String>();
System.out.println(set.isEmpty());
}
}