http://stackoverflow.com/questions/5690351/java-stringlist-toarray-gives-classcastexception
編譯并不會報錯,但是運行時會檢查類型,這個時候在數(shù)組做強制轉(zhuǎn)換的時候出現(xiàn)問題
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<String> recipientSet1 = new HashSet<>();
recipientSet1.add("wdxxlanswer@gmail.com");
String[] recipients1 = (String[]) recipientSet1.toArray(); // 問題出在這里
System.out.println(recipients1.length);
// Solution 解決方案
Set<String> recipientSet2 = new HashSet<>();
recipientSet2.add("wdxxlanswer@gmail.com");
String[] recipients2 = recipientSet2.toArray(new String[recipientSet2.size()]);
System.out.println(recipients2.length);
}
}