2010-12-14 67 views
2

Ok有關javas泛型,iterable和for-each循環的問題。問題在於,如果我聲明我的'測試'類是無類型的,那麼我將失去關於我所有函數的所有通用信息,因爲每個函數都不會這樣。Java無類型泛型類,刪除它們的功能泛型類型

public class Test<T> implements Iterable<Integer>{ 

    public Test() {} 

    public Iterator<Integer> iterator() {return null;} 

    public static void main(String[] args) { 
     Test t = new Test(); 

     //Good, 
     //its returning an Iterator<object> but it automatically changes to Iterator<Integer> 
     Iterator<Integer> it = t.iterator(); 

     //Bad 
     //incompatable types, required Integer, found Object 
     for(Integer i : t){ 
     } 
    }Untyped generic classes losing 
} 

當 '測試T' 是非類型化的,則 '迭代()' 功能返回 '遊標' 而不是 '迭代<整數>'。

我不完全確定它背後的原因,我知道一個解決方案就是在測試<上使用通配符? > t = new test()'。然而,這不是理想的解決方案。
他們有什麼辦法只編輯類聲明及其函數,併爲每個循環工作無類型?

+0

如果使用原始類型,在方法仿製藥將被忽略(見最新的Java謎題分期付款)。不要使用原始類型。最近版本的javac應該給出警告。 – 2010-12-15 01:04:24

+0

感謝您的視頻鏈接,在他們的非常有趣的東西。 背後的推理現在變得更加流行。 – user542481 2010-12-15 18:20:54

回答

3

你應該只做到以下幾點:

public class Test implements Iterable<Integer>{ 

刪除泛型類型都在一起。你的Test類是不通用的。它只是實現一個通用接口。聲明一個泛型類型是沒有必要的。這也將有利於刪除您所得到的通用警告。

@Eugene說得很好。如果你其實想一個通用Test類型,應聲明Test作爲一個通用的迭代:

你應該只做到以下幾點:

public class Test implements Iterable<Integer>{ 

刪除泛型類型都在一起。你的Test類是不通用的。它只是實現一個通用接口。聲明一個泛型類型是沒有必要的。這也將有利於刪除您所得到的通用警告。

public class Test<T> implements Iterable<T>{ 

,然後確保你Test通用的,當你實例化。

Test<Integer> t = new Test<Integer>; 

然後調用for(Integer i: t)將編譯。

2

您應該這樣寫:

public class Test implements Iterable<Integer>{ 
    ... 

或實際泛型化類:

public class Test<T> implements Iterable<T> { 

    public Iterator<T> iterator() {return null;} 

    public static void main(String[] args) { 
     Test<Integer> t = new Test<Integer>(); 

     Iterator<Integer> it = t.iterator(); 

     for(Integer i : t){ 
     } 
    } 
} 
+0

正是我開始寫的。 +1 – 2010-12-14 21:02:35

+0

是的,可以工作,但你可以遇到類似的情況。 「public class Vertex implements Iterable >」。對於圖表示例。這很奇怪,但你可以得到你的迭代沒有返回調用它的類的情況。我的錯誤我很難解釋它。 – user542481 2010-12-15 17:46:56

+0

這是完全不同的問題。在這種情況下,你的iterator()方法必須返回Iterator >,就像那樣簡單。另一方面,你可能不需要澄清你的Iterable實現,並且可以聲明它更通用,如實現Iterable 而不是Iuterrable >。 – 2010-12-15 21:11:41