Search code examples
javaspringgenericscompiler-warningsunchecked

Unchecked call to 'forEach()' as a member of raw type 'java.lang.Iterable'


I am getting this compiler warning. This is my class with interface and method used (other staff omitted):

public class Controller extends BaseController {

//interface
public interface MyInterface<T extends Iterable<? super T>> {
    List<T> getList();
}

//method call
updateJoinTable(request.getProductGrades().size(), instance::getProductGrades);

//method
private static void updateJoinTable(Integer LastValidElement, MyInterface myInterface) {
    myInterface.getList().subList(LastValidElement, myInterface.getList().size())
          .forEach(i ->myInterface.getList().remove(i));
}
}

The last part with forEach is causing warning.

Now, at first the code was without:

<T extends Iterable<? super T>>

but I've seen a lot of similar cases here on SO, mostly with comparable and I understood by reading the solutions, that problem is that my generic types are bonded to a type that itself has a type, but I haven't provided one, so it's raw - then I added that line to interface and expected warning to go away. But it's still there. Do you have any ideas what I should do to get rid of it?


Solution

  • The immediate issue is that MyInterface myInterface is a raw type. Make it non-raw, e.g.:

    private static void updateJoinTable(Integer LastValidElement, MyInterface<?> myInterface) {
    

    Additionally, you might want to consider not using forEach. It looks like you're just trying to chop off the tail of the list:

    List<?> list = myInterface.getList();
    list.subList(LastValidelement, list.size()).clear();