2014-02-06 2 views
0

사람들 원래 Java가 null 값에 대한 검사를 무시하고 있다고 생각했습니다.주의 깊게 검사하고 디버깅 한 후에 거대한 프로그램의 일부인 바보 같은 코드가 있습니다. 전체 메서드를 게시 할 수는 없지만이 메서드를 통해 포인트를 얻어야합니다.InternetAddress의 인스턴스화로 인해 NPE가 발생합니다.

public class NullCheck { 
public static void main(String[] args) { 

    ArrayList<String>copied = new ArrayList<String>(); 
    copied.add("[email protected]"); 
    copied.add(null); 

    /* Built MimeMessage msg = new MimeMessage(session); */ 
    InternetAddress[] copiedPeople = new InternetAddress[copied.size()]; 
    for (int i = 0; i < copied.size(); i++) 
    { 
     String recCC = (String)copied.get(i); 
     if ((recCC != null) && (!recCC.equalsIgnoreCase(""))) { 
      try { 
       copiedPeople[i] = new InternetAddress((String)copied.get(i)); 
      } catch (AddressException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    } 
      // I crash here 
// msg.addRecipients(Message.RecipientType.CC, copiedPeople); 
} 
} 

이 코드는 처음 14 번 반복해도 문제가 없으므로 괜찮습니다. 다시 나는 null 체크가 무시 당하고 있다고 생각했지만 그렇지 않다! InternetAddress 배열이 인스턴스화되면 [null, null]로 설정되므로 for 루프는 ArrayList의 두 번째 항목을 제대로 무시하지만 addRecepients에 대한 호출이 완료되면 ArrayList는 여전히 인스턴스화에서 두 번째 null을 갖습니다. 어떻게 해결할 수 있을까요?

답변

0

다른 알고리즘을 사용해야합니다. addRecipients는받는 사람 중 누구도 null이 아니길 요구합니다. 이 경우 정확히 길이의 배열을 전달해야합니다. 가장 쉬운 방법은 복사 된 모든 null 요소를 제거한 다음 copied.toArray()를 두 번째 매개 변수로 전달하는 것입니다. 복사 한 ArrayList를 변경할 수없는 경우

int i = 0; 
while(i < copied.size()) 
{ 
     String recCC = (String)copied.get(i); 
     if ((recCC == null){ 
      copied.remove(i); 
     } 
     else{ 
      i++; 
     } 
} 
msg.addRecipients(Message.RecipientType.CC, copied.toArray()); 

는, 당신은 널 (null)없이 버전에 toArray를 사용, 그것으로 널 (null)을 추가하지, 먼저 새 배열 목록을 만들 수 있습니다.