generics - List<interfaceI> vs List<? extends InterfaceI> in java -
arraylist list<interfacei>
, list<? extends interfacei>
both have objects of classes implementing interfacei. when should used?
suppose foo
, bar
2 classes implementing interfacei
.
the second 1 (list<? extends interfacei>
) doesn't allow adding list (except null), since type list contains unknown: list<foo>
or list<bar>
: don't know.
so use notation method argument, when want method read elements of list passed argument, , want caller able call method list<interfacei>
, list<foo>
or list<bar>
. using list<interfacei>
argument accept lists of type list<interfacei>
.
let's take concrete example: want compute maximum double value of list of numbers. such method doesn't need add or set list. iterating on elements, each number , compute maximum. signature be
public double max(list<number> list);
but then, won't able do
list<integer> ints = new arraylist<>(); max(ints);
the way call method do
list<number> ints = new arraylist<>(); max(ints);
whereas if declare method as
public double max(list<? extends number> list);
then can do
list<integer> ints = new arraylist<>(); list<long> longs = new arraylist<>(); max(ints); max(longs)
Comments
Post a Comment