简体   繁体   English

带有扩展名的泛型的正确Java语法

[英]correct java syntax for generics with extends

this is a piece of code i'm struggling with. 这是我在努力的一段代码。

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 line that does not work gives me compiler error: 不起作用的行给了我编译器错误:

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

I don't understand this error. 我不明白这个错误。 If I remove all the generics in Manager class it is working but type unsafe. 如果我删除Manager类中的所有泛型,则可以正常工作,但键入不安全。 How should I do this in correct Java? 我应该如何在正确的Java中执行此操作?

That's inherently unsafe. 这本质上是不安全的。

What happens if you add a Channel<MyThing> to the list, then call OtherMethod() with a YourThing ? 如果将Channel<MyThing>添加到列表,然后使用OtherMethod()调用OtherMethod()发生YourThing

You should make the entire class generic (and make the members non-static), and use the same T for the channels and the parameter. 您应该使整个类通用(并使成员成为非静态),并对通道和参数使用相同的T

You need a type parameter for your method public <T extends Something> void method(T foo) 您的方法需要一个类型参数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
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM