<? super E> and <? extends E> for List

前端 未结 5 1157
无人共我
无人共我 2020-12-10 02:22

Having the following simple class structure:

class A {
}

class B extends A {
}

class C extends B {
}

I\'m creating an ArrayList to keep o

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 02:40

    "? extends A" means "some type derived from A (or A itself)". So for instance, a List is compatible with List - but you shouldn't be able to add a FileOutputStream to such a list - it's meant to be a List! All you know is that anything you fetch from the list will be an OutputStream of some kind.

    "? super A" means "some type which is a superclass of A (or A itself)". So for instance, a List is compatible with List. You can definitely add a ByteArrayOutputStream to such a list - but if you fetch an item from the list, you can't really guarantee much about it.

    See Angelika Langer's Generics FAQ for much more information.

提交回复
热议问题