Skip to content
Advertisement

Wildcard not allowed for Iterable in Java

I have following code setup. But this is not allowed as wildcard is not allowed for Iterable.

public interface CustomInterface extends Iterable<? extends MyBaseType>{....}

CustomTypeA extends MyBaseType{....}

class CustomImpl implements CustomInterface {
 List<CustomTypeA> listA = new ArrayList();

 @Override
 public Iterator<CustomTypeA> iterator() {
    return listA.iterator();
 }
}

What actually Java tries to a achieve here by not allowing this? What modifications would get this working?

Advertisement

Answer

When a class instance is created, it invokes the initializer of the super type. But you can’t use wildcards for instance creation, hence your compiler giving an error. You must provide the exact type here.

Here’s an excerpt from JLS ยง15.9

If TypeArguments is present immediately after new, or immediately before (, then it is a compile-time error if any of the type arguments are wildcards

One workaround would be to parameterize your class and pass that type variable to the Iterable interface implementation.

interface CustomInterface<T extends MyBaseType> extends Iterable<T>{

} 
Advertisement