2

I'm trying to create a method which takes as an argument a collection of some common supertype of two classes, A and B (and then adds instances of A and B to the collection). Something like the following:

public <T, A extends T, B extends T> void foo(Collection<T> collection);

Of course, that doesn't work since Java interprets A and B here as type parameters, overshadowing the concrete types A and B. Since I know the type hierarchy, I know the lowest common ancestor of A and B, say C, and can just have:

public void foo(Collection<? super C> collection);

I would rather not do this, though, since I very well might change the type hierarchy and would like foo to be as generic as possible.

Ellis Michael
  • 962
  • 1
  • 8
  • 14
  • No, there's no general way to do this better than what you have. – Louis Wasserman Apr 10 '15 at 21:30
  • Why are you resistant to your solution? When designing API's with generic parameters there is a "Producer extends, Consumer super" principle. Since your method consumes `C` instances, `super` is the logical way to use a wildcard in your API and have your method be as flexible as possible. – scottb Apr 10 '15 at 23:03

0 Answers0