Suppose I have a class that implements an interface:
public class A implements IB
and I have a List<A> that I would like to reference to: List<? implements IB> list.
So that I can code: for (IB item : list) etc.
Can it be done somehow in Java? There is no <? implements ...> possibility.
What am I missing?
If you meant that class A implements IA, rather than IB, then your code should be just fine saying
since all As are, by definition IAs.
Meanwhile, there is no wildcard for
<? implements C>. There is<? extends C>, andCcan be an interface or a class; however, this isn’t necessary for what you seem to be trying to do.If you want expressly to say
for (IA item : list)because you’re not guaranteeing that items in that list areAs, but are guaranteeing that they areIAs, then I think you have a slight problem (I can’t tell for sure, since you didn’t say where this list processing code is located). AList<A>is not aList<IA>by definition; if you’re building aList<A>and then passing it to a method that expects aList<IA>, you’ll get a compile time error. You can, however, create aList<IA>and fill it withAs. The reason for this is explained in Java’s tutorial on generics.