Java ArrayList of ? extends Interface

前端 未结 4 1187
长情又很酷
长情又很酷 2020-12-12 02:13

I have a group of classes that all implement a validation interface which has the method isValid(). I want to put a group of objects--all of different classes--

4条回答
  •  一向
    一向 (楼主)
    2020-12-12 02:50

    If a generic class's T is , then the only thing you can pass to a method that takes T is null -- not any subclass that extends Foo.

    The reason is that List doesn't mean "a list of things that extend Validation". You can get that with just List. Instead, it means "a list of some type, such that that type extends Validation."

    It's a subtle distinction, but basically the idea is that List is a subtype of List, and you therefore don't want to be able to insert anything into it. Think of this case:

    List foos = new ArrayList<>();
    List validations = foos; // this is allowed
    validations.add(new BarValidation()); // not allowed! this is your question
    FooValidation foo = foos.get(0);
    

    If the third line were allowed, then the last line would throw a ClassCastException.

提交回复
热议问题