我想要使一個LinkedSet對象類實現一個修改後的Set接口。當我嘗試檢查firstNode是否指向null時,我得到一個NullPointerException。我不確定如何解決這個問題。獲取NullPointer實現LinkedSet
這是相關的代碼。
構造整體設置對象
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()
這裏是節點的專用內部類對象
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
}
}
firstNode = NULL ;在你的構造函數拋出 –
除了其他建議:在'getSize()'我相信你應該初始化'size'爲0並使用'current!= null'作爲'while'條件。 –