我正在創建一個由數組支持的泛型類型的堆棧。當我嘗試創建一個泛型類型數組時,Java不允許我。我被告知必須創建一個Object類型的數組並將其轉換爲泛型類型。我已經鑄造了我的Object數組來輸入,但是我怎樣才能處理Java一直給我的Unchecked Type錯誤?將對象數組轉換爲泛型類型
public class AStack<T>{
// Create a stack with the default capacity 10. The stack expands
// its internal array when the number of elements pushed() into it
// would exceed the internal capacity.
Object arr[];
int top=-1;
public AStack(){
int defSize=10;
arr = (T[])new Object [defSize];
}
這是我到目前爲止的地方。
UPDATE: 我創建對象數組,然後鑄造返回類型在方法結束時爲T類型。
我沒有看到我的做法有問題,怎麼了? – ChrisAngj
你可以這樣做:像這樣創建一個通用的AStack類AStack ....聲明數組像E [] arr =(E [])new Object [size]; - >這會產生一個警告,但是你可以忽略這個,因爲在類型擦除E的時候,反正你會留下一個Object數組....現在你的方法都可以假設這個數組是E類型的而且沒有強制轉換。 ... –
Madhusudhan
http://stackoverflow.com/questions/14524751/cast-object-to-generic-type-for-returning – DarkV1