![](/img/trans.png)
[英]Why does Java's Collection<E>.toArray() return an Object[] rather than an E[]?
[英]Why does Collection<E>#toArray() not return E[]?
這是因為如果不知道Type Class<T>
類型就無法實例化T
類型的數組。 將此與toArray(T[] array)
對比,后者具有以下源(來自LinkedList
示例)。 請注意,傳入的數組不僅用作可能的容器,還可以實例化該類型的新數組。 如果T
不是E
的超類,則此代碼將引發異常。 如果無法將對象添加到數組中。
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
int i = 0;
Object[] result = a;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
if (a.length > size)
a[size] = null;
return a;
}
Java中的泛型使用稱為類型擦除的技術實現。 這意味着泛型類的實例沒有關於其泛型類型的任何信息。 考慮一下
List<String> list = new ArrayList<String>();
list.toArray();
由於list不知道它的泛型類型,它只能創建Object []
數組容器具有關聯的項數據類型,在運行時保留。 如果構造一個Object數組然后添加字符串,則該對象將不可轉換為String []:
Object[] objArr = new Object[] {"a", "b"};
String[] strArr = (String[]) objArr; //Produces ClassCastException
您還可以注意到在將錯誤類型的項添加到數組時,如何在運行時使用此數組屬性:
String[] strArr = new String[] {"a", "b"};
Object[] objArr = (Object[]) strArr; //Legal this time
objArr[0] = 15; //Produces ArrayStoreException
泛型類型參數在運行時被擦除,因此當您調用toArray()時,JVM不知道要在運行時創建哪種特定的數組類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.