Because of these fundamental differences, arrays and generics do not
mix well. For example, it is illegal to create an array of a generic
type, a parameterized type, or a type parameter. None of these array
creation expressions are legal: new List[], new List[], new
E[]. All will result in generic array creation errors at compile time.
Generally speaking, arrays and generics don’t mix well. If you find
yourself mixing them and getting compile-time errors or warnings, your
first impulse should be to replace the arrays with lists.
因為數組和泛型不對付, 所以在不做強制類型轉換的情況下, 我們是沒有辦法得到一個泛型數組的實例的, 編譯器會限制此類情況發生(new E[], list .toArray());
為什麼陣列和泛型不對付, Effective Java裡面有例子. 根本原因在於:
Arrays are covariant. This scary-sounding word means simply that if
Sub is a subtype of Super, then the array type Sub[] is a subtype of
Super[].
/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list in
* proper sequence
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
這個Effective Java第二版裡有說到, Item25.
給出例子說明我的理解, 類似的程式碼, 在泛型集合下, 會在靜態編譯階段報錯; 而泛型數組在運行階段給出ArrayStoreException:
沒有泛型數組,這一說
toArray()
方法有兩種,帶參和不帶參.帶參的情況下,參數就是一個泛型數組,如
T[] a
,相當於你手動構造一個數組,傳入方法中.toArray()
內部是一個copy的實現.舉兩個例子.
1:
String[][] str_a = (String [][]) arr.toArray(new String[0][0]);
2 :
String[][] a = new String[<size>][size];
String [][] str_a = (String [][]) arr.toArray(a);
當然 要保證轉型成功,不然會引發ClassCastException.
--------------------------分割線------------------- ------
以下是原始碼中是實作,其實就是一個copy操作.