2014-12-03 44 views
0

這是我正在努力的一段代碼。正確的java語法與擴展的泛型相關

public class Channel<T extends Something>{ 
    public Channel(){} 
    public void method(T something){} 
} 

public class Manager{ 
    private static ArrayList<Channel<? extends Something>> channels 
     = new ArrayList<Channel<? extends Something>>(); 
    public static <T extends Something> void OtherMethod(T foo){ 
     for(Channel<? extends Something> c : channels) 
     c.method(foo); // this does not work 
    } 
} 

行不行給我的編譯器錯誤:

The method method(capture#1-of ? extends Something) in the type Channel<capture#1-of ? extends Something> is not applicable for the arguments (T) 

我不明白這個錯誤。如果我刪除了Manager類中的所有泛型,它正在工作,但輸入不安全。 我應該如何在正確的Java中執行此操作?

回答

1

你需要一個類型參數的方法public <T extends Something> void method(T foo)

public class Channel<T extends Something> { 
    public Channel() { 
    } 

    public <T extends Something> void method(T foo) { 
    } 
} 

public class Manager { 
    private static ArrayList<Channel<? extends Something>> channels = new ArrayList<Channel<? extends Something>>(); 

    public static <T extends Something> void OtherMethod(T foo) { 
    for (Channel<? extends Something> c : channels) 
     c.method(foo); // this does not work 
    } 
} 
1

這本質上是不安全的。

如果將Channel<MyThing>添加到列表中,然後使用YourThing調用OtherMethod(),會發生什麼情況?

您應該使整個類具有通用性(並且使成員非靜態),並且對通道和參數使用相同的T

+0

從未發生過。我簡化了代碼。 OtherMethod會在他的頻道中搜索頻道,並使用它。請不要告訴我,我的代碼不是很優雅。請告訴我爲什麼這是不正確的。 – ArcticLord 2014-12-03 15:21:55

+1

@ ArcticLord:你的代碼被寫入的方式,這是不正確的。如果你沒有顯示你的實際代碼,我不能幫你。 – SLaks 2014-12-03 15:24:42