0

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. How should I do this in correct Java?

2 Answers 2

1

You need a type parameter for your method 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
   }
}
Sign up to request clarification or add additional context in comments.

Comments

1

That's inherently unsafe.

What happens if you add a Channel<MyThing> to the list, then call OtherMethod() with a 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.

2 Comments

Never happens. I simplified the code. OtherMethod would search in his channels for a Channel<YourThing> and would use this. Please don't tell me that my code is not ellegant. Please tell me why it is not correct.
@ArcticLord: The way your code is written, that is not true. If you aren't showing your actual code, I can't help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.