2013-10-22 45 views
0

空指針異常,我想創建一個方法「headSet」,創建並返回一個新的TreeSetset,這是在叫TreeSet這小於「前」參數元素的所有值的值。在遞歸方法

我可以得到所有正確的遍歷,並且我在Net Beans中進行了調試,新集合確實包含它應該引發異常之前的所有值。我只是想不通爲什麼當我打電話headSet(n.right,before,set) ..特別是n.right ..它打破了。如果沒有中斷,它會工作得很好。

編輯:當我有問題的線路,headSet(n.right,before,set),運行該程序,那麼所有3 headSet()方法調用主遞歸幫手是在堆棧跟蹤。當我註釋掉這一行時,除了錯誤的樹遍歷之外,沒有任何問題。

這是被調用方法的主要公共觸發遞歸助手:

public SortedSet<E> headSet(E before){ 
    SortedSet<E> set = new SearchTreeSet<E>(); 
    headSet(root, before, set); 
    return set; 
} 

其中根是在被叫TreeSet第一節點。

主要遞歸幫手:

private void headSet(Node n, E before, SortedSet<E> set) { 
    int comp = myCompare(n.data, before); 

    if (comp < 0){ //n.data is less than before 
    // add node n to the new set 
    if (n.data != null) { //It shouldn't be null but I just wanted to eliminate NPE sources 
     set.add(n.data); 
    } 
    // all nodes to the left are added automatically with a separate recursive function 
    headSet(n.left, set); 

    // test nodes to the right 

    //////////////The next statement forces a null pointer exception //////// 
    headSet(n.right, before, set); 
    } 
    // n.data is greater than or equal to 'before' 
    else { 

     // move to the left and retest 
     headSet(n.left, before, set); 
    } 
} 

第二遞歸函數不比較,它只是將所有節點跳轉到新的排序樹集合「設置」

private void headSet(Node n, SortedSet<E> set){ 
    if (n.data != null){ // 'if statement' is to eliminate NPE sources, it normally shouldn't be null 
    set.add(n.data); 
    } 
    if (n.left != null) { headSet(n.left, set); } 
    if (n.right != null) { headSet(n.right, set); } 
} 

解決 : 謝謝你們!那是它..我不相信我沒有看到它。

這是我改變來解決這個問題:

if (n.left != null) { 
    headSet(n.left, set); 
} 

if (n.right != null) { 
    headSet(n.right, before, set); 
} 

而且還

if (n.right != null) { 
    headSet(n.right, before, set); 
} 
+0

你是否得到NullPointerException? –

+0

調試並查看實際爲空?另外,實際的堆棧跟蹤可能會有所幫助。 – Taylor

+0

也許你在最後一個節點,沒有比它大的東西。檢查你的headSet中的n.right!= null(n.right,before,set) – Keerthivasan

回答

0

首先,我不認爲你會實現你與SortedSet的計劃什麼。 因爲當您將對象添加到SortedSet時,它會根據您要添加到其中的對象定義的compareTo方法對對象的內部順序進行排序。現在在你的情況下,最簡單的事情就是實現Comparable到n.data類。當你這樣做時,你可以使用你在myCompare方法中定義的邏輯。現在按任意順序將n.data添加到SortedSet中,SortedSet將使用其自然順序對它們進行組織。如果您確實想要以編程方式維護訂單,請使用List。現在讓我們說你擺脫了NPE,然後你想打印保存在Set中的n.data,並且想驗證你的排序算法是否有效,你不能這麼做,因爲set會根據它的自然返回對象列表排序順序。