01. ClassCastException (String List ToArray)

http://stackoverflow.com/questions/5690351/java-stringlist-toarray-gives-classcastexception
컴 파일 이 잘못 되 지 는 않 지만 실행 할 때 유형 을 검사 합 니 다.이 럴 때 배열 이 강제 변환 을 할 때 문제 가 발생 합 니 다.
The class cast exception happened just because toArray() returns Object[]. Surely Object[] cannot cast to String[]. JDK8 API: List toArray
import java.util.HashSet;
import java.util.Set;

public class ToArrayGivesClassCastException {
    public static void main(String[] args) {
        // java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
        Set recipientSet1 = new HashSet<>();
        recipientSet1.add("[email protected]");
        String[] recipients1 = (String[]) recipientSet1.toArray(); //       
        System.out.println(recipients1.length);

        // Solution     
        Set recipientSet2 = new HashSet<>();
        recipientSet2.add("[email protected]");
        String[] recipients2 = recipientSet2.toArray(new String[recipientSet2.size()]);
        System.out.println(recipients2.length);
    }
}

좋은 웹페이지 즐겨찾기