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.
/**
* 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操作.