最近學習jdk1.8源碼時,發現ArrayList(Collection<? extends E> c)這個構造函數中,有句有意思的描述:c.toArray might (incorrectly) not return Object[] (see 6260652),
做了一些實驗后均沒能解釋why!而后發現通過正常方式創建的Collection參數都是不會有問題的,問題出在這個Collection參數如果通過某些方式創建得到,就會出現如題的問題!
public static void main(String[] args) { Integer[] array = {1, 2}; // 通過Arrays轉換成的List,保留了原本的類型 List list = Arrays.asList(array); // 即使再將其轉換為Object類型的數組,還是原本的類型 Object[] array3 = list.toArray(); System.out.println("通過數組轉換:" + (array3.getClass() == Object[].class)); // 如果是創建的集合,則類型可以轉換 List<Integer> li = new ArrayList<Integer>(); System.out.println("通過集合轉換:" + (li.toArray().getClass() == Object[].class)); }
運行結果: