2016-06-13 127 views
0

我有下面的代碼,我一直在爲一個學校任務進行改進,但是有一個空指針異常讓我瘋狂。Java,空指針異常

這裏是我的代碼:

public static <AnyType extends Comparable<? super AnyType>> 
    void difference(List<AnyType> L1, List<AnyType> L2, List<AnyType> Difference){ 

     if(L1 == null){ 
      Difference = null; 
     } 
     else if(L2 == null || L1.isEmpty() || L2.isEmpty()){ 
      Difference = L1; 
     } 
     else{ 
      Iterator<AnyType> iterator1 =L1.listIterator(); 
      Iterator<AnyType> iterator2 =L2.listIterator(); 

      AnyType a = iterator1.next(); 
      AnyType b = iterator2.next(); 

      while(a!=null || b!=null){ 
       int comp = a.compareTo(b); 
       if(comp > 0) 
        b =(iterator2.hasNext()) ? iterator2.next(): null; 

       else if(comp < 0){ 
        Difference.add(a); 
        a = (iterator1.hasNext())? iterator1.next(): null; 

       } 
       else { 
        a = (iterator1.hasNext())? iterator1.next() : null; 
        b = (iterator2.hasNext())? iterator2.next() : null; 
       } 
      } 
      if(b==null){ 
       while(a!=null){ 
        Difference.add(a); 
        a = iterator1.next(); 
       } 
      } 
     } 
     System.out.println("Difference Set: " + Arrays.toString(Difference.toArray())); 
    } 

在while循環,當是空的程序不斷進入的同時,並沒有被應該發生的。誰能告訴我爲什麼會發生這種情況? 我使用的測試數據是:

List<Integer> list3 = Arrays.asList(1,2); 
     List<Integer> list4 =Arrays.asList(5,17); 
     List<Integer> listR = new ArrayList<>(); 

     ListsSets.difference(list3, list4, listR); 

後是空的,而應該是不會再執行,但它在某種程度上發生。

+2

您使用'||',所以只有其中一個必須爲真 – Ramanlfc

+0

,因爲您在用作while while條件的表達式中輸入了'OR'條件而不是&&運算符。所以它應該進入while循環內部,即使a爲null但b不爲null –

回答

0

使用&&,因爲使用||將使您的if條件通過,如果其中一個爲真。因此,如果a非空,但b爲空,則您的代碼仍在執行。