2014-11-05 5 views
-1

정렬하려고하는 특정 클래스의 ArrayList가 있습니다. 그러나 정렬 중에 NullPointerException이 발생합니다. 배열에서 예외를 일으키는 요소를 찾으려면 try-catch를 사용하여 내 명령을 래핑했습니다. 문제가되는 요소를 파악하기 위해 catch를 검사 할 수 있습니까?NullPointerException을 검사하십시오. 원인

List<SingleMeasurementValuePoint> sortedList = new ArrayList<SingleMeasurementValuePoint>(deviceMeasurementPoints); 
    try { 
     Collections.sort(sortedList, new TimeAndComponentSort()); 
    } catch (Exception e) { 
     System.out.println(); 
    } 

비교기 내의 코드, TimeAndComponentSort는 예 :

public class TimeAndComponentSort implements Comparator<SingleMeasurementValuePoint> { 

@Override 
public int compare(SingleMeasurementValuePoint point1, SingleMeasurementValuePoint point2) { 
    int val = point1.compareTo(point2); 
    if (val == 0) { 
     return point1.getComponentId().compareTo(point2.getComponentId()); 
    } 
    else { 
     return val; 
    } 
} 
} 
+1

왜 디버거를 사용하지 않습니까? – manouti

+2

코드를 Comparator - TimeAndComponentSort에 게시 할 수 있습니다. – BatScream

+1

나는 디버거를 사용하고 캐치 안에 서 있습니다. 어떻게 ArrayList 내의 4500 요소 중 하나가 예외의 원인인지 감지 할 수 있습니까? – user3370773

답변

0

난 당신이 스택 추적보고에서 어떤 요소를 결정할 수 있다고 생각하지 않습니다

다음

코드입니다 Listnull이었다. Listnull 개의 요소가있는 경우 가장 쉬운 해결 방법은 Comparatornull (s)으로 처리하는 것입니다. 또한 을 사용하여 null (으)로 로그인 할 수 있습니다. 기본적으로,

@Override 
public int compare(SingleMeasurementValuePoint point1, 
     SingleMeasurementValuePoint point2) { 
    if (point1 == null && point2 == null) { 
     System.out.println("null point1 and point2"); 
     return 0; 
    } else if (point1 == null) { 
     System.out.println("null point1"); 
     return -1; 
    } else if (point2 == null) { 
     System.out.println("null point2"); 
     return 1; 
    } 
    int val = point1.compareTo(point2); 
    if (val == 0) { 
     return point1.getComponentId().compareTo(
       point2.getComponentId()); 
    } else { 
     return val; 
    } 
} 

같은 그건 아직 무엇을 원래의 인덱스에있는 요소가 null했다 당신에게 말할 것이다. 즉, 만약 당신이 정말로 다음 필요 당신은 당신의 catch 블록 (들)이 자신의 Exception (들)

을 기록해야 마지막으로

public static <T> int findFirstNull(List<T> al) { 
    for (int i = 0, len = al.size(); i < len; i++) { 
     if (al.get(i) == null) { 
      return i; 
     } 
    } 
    return -1; 
} 

처럼 처음 null (또는 -1)의 인덱스를 반환하는 방법을 쓸 수있다

} catch (Exception e) { 
    // System.out.println(); 
    e.printStackTrace(); 
} 
관련 문제