2016-06-13 6 views
0

나는 학교 과제를 위해 정련하고있는 다음 코드를 가지고 있지만, 나를 미치게 만드는 널 포인터 예외가있다. A는 프로그램이 동안으로가는 유지 null이며,이는 일이 안 될 때, while 루프에자바, null 포인터 예외

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())); 
    } 

:

여기 내 코드입니다. 아무도 왜이 일이 일어 났는지 말해 줄 수 있습니까? 내가 테스트하는 데 사용하고 데이터는 다음과 후

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

     ListsSets.difference(list3, list4, listR); 

이는 null 동안 다시 실행되지 않을 예정이지만 어떻게 든 일이다.

+2

당신이'||'를 사용하고 있기 때문에 while 조건으로 사용 된 표현식 안에 && 연산자 대신에 'OR'조건을 입력했기 때문에 그 중 하나만 참이어야합니다 ( – Ramanlfc

+0

). 따라서 a가 null이지만 b가 null이 아니더라도 while 루프 안으로 들어가야합니다. –

답변

0

||을 사용하면 해당 조건 중 하나가 참인 경우 조건을 통과하게되므로 &&을 사용하십시오. 결과적으로 a이 아니고 b 인 경우 코드가 계속 실행됩니다.