2014-12-03 48 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