-3

consider the following code:

public class ListDemo {

    List<Inner> inners;

    public ListDemo() {
        this.inners = new ArrayList<>();
    }

    private void load(){
        SomeClzz.load(inners);
    }

    private class Inner implements TestInterface {

        @Override
        public void bla() {
            System.out.println("Bla");
        }

    }
}

with the interface:

public interface TestInterface {
    public void bla();
}

and the class:

public class SomeClzz {
    public static void load(List<TestInterface> test){
        for (TestInterface testInterface : test) {
            testInterface.bla();
        }
    }
}

I created this fake code based on a real world example, because I wanted to see if I could isolate the issue and found the that the load method had an error.

Why is it that SomeClzz.load(inners); gives an error that inners can't be cast from a List<Inner> to a List<TestInterface>?

Rik Schaaf
  • 1,101
  • 2
  • 11
  • 30

1 Answers1

1

Simple change will make it work:

public static void load(List<? extends TestInterface> test){
    for (TestInterface testInterface : test) {
        testInterface.bla();
    }
}

UPDATE: You can find the answer here.

In short.

List<Inner> is not a subtype of List<TestInterface>.

This is a common misunderstanding when it comes to programming with generics, but you need to understand this, as generics are very important frequently used.

Beri
  • 11,470
  • 4
  • 35
  • 57