2013-10-15 73 views
0

我遇到了未經檢查的轉換的警告。我不知道如何解決警告。警告:[unchecked]未勾選強制轉換。泛型

編譯器錯誤似乎選擇list = (E[]) new IntKeyed [size];
這是我們所假設的使用字母代碼的代碼。
我們正試圖使用​​泛型因此「E」。

所以我想我必須在這個代碼中的某處瘋狂。 當我查找錯誤時,它似乎與ArrayLists有關,但我不知道使用ArrayList

也許我應該是ArrayLists?會改變這些修復警告嗎?我的代碼中也有一個不完整的異常處理問題。但我認爲這與陣列問題是隔離的。

任何錯誤,你可以找到將有助於指向正確的方向。謝謝。

public abstract class MyArrayList<E> implements IntKeyed 
{ 

private final int DEFCAP = 50; 
private int origCap; 
private int numElements; 
private E[] list; 

public MyArrayList() 
{ 
    origCap = DEFCAP; 
    list = (E[]) new IntKeyed [origCap]; *******Error Here 
} 

public MyArrayList(int size) throws Exception 
{ 
    size = DEFCAP; 
    if(size > 0) 
    { 
     list = (E[]) new IntKeyed [size]; *******Error Here 
     origCap = size; 
    } 
    else 
    { 
     throw new ArrayStoreException(); 
     System.out.println("List size is invalid"); 
    } 
    list = (E[]) new IntKeyed [size];   *******Error Here 
} 

private void enlarge() 
{ 
    E[] larger = (E[]) new IntKeyed [list.length + origCap]; *******Error Here 
    for(int i = 0; i < list.length; i++) 
    { 
     larger[i] = list[i]; 
    } 
    list = larger; 
} 

javac -Xlint:unchecked MyArrayList.java 編譯我得到:

MyArrayList.java:29: warning: [unchecked] unchecked cast 
    list = (E[]) new IntKeyed [origCap]; 
       ^
required: E[] 
found: IntKeyed[] 
where E is a type-variable: 
E extends Object declared in class MyArrayList 
MyArrayList.java:37: warning: [unchecked] unchecked cast 
     list = (E[]) new IntKeyed [size]; 
        ^
required: E[] 
found: IntKeyed[] 
where E is a type-variable: 
E extends Object declared in class MyArrayList 
MyArrayList.java:45: warning: [unchecked] unchecked cast 
    list = (E[]) new IntKeyed [size]; 
       ^
required: E[] 
found: IntKeyed[] 
where E is a type-variable: 
E extends Object declared in class MyArrayList 
MyArrayList.java:117: warning: [unchecked] unchecked cast 
    E[] larger = (E[]) new IntKeyed [list.length + origCap]; 
        ^
required: E[] 
found: IntKeyed[] 
where E is a type-variable: 
E extends Object declared in class MyArrayList 
MyArrayList.java:43: error: unreachable statement 
     System.out.println("List size is invalid"); 
     ^
1 error 
4 warnings 

回答

1

警告不是問題,問題是拋出異常後不到的語句。

它應該是這樣的:

System.out.println("List size is invalid"); 
throw new ArrayStoreException(); 

如果認爲自己的類型轉換應該努力 - 在方法或語句級(小範圍越好)添加@SuppressWarnings("unchecked")。編譯器不會發出任何消息,但如果您的投射錯誤,您仍然會在運行時遇到異常。

1

list = (E[]) new IntKeyed [origCap];警告實際上意味着通用E被硬編碼爲IntKeyed所以你傳進去的E,您list將始終保持IntKeyed型。

在你的情況下,泛型使用似乎並不適合,因爲你已經在爲此目的實現特定的接口。