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

你可能感兴趣的:(01. ClassCastException (String List ToArray))