Where can we use ArrayList <? extends My_Class>
3 answers
A commonly used abbreviation for describing these keywords: PECS: producer extends - consumer super.
So, if you use "extends", your collection produces elements of this type. So you cannot add to it, you can only take it.
A usage example would be to provide the client with your list API:
public List<? extends CharSequence> getFoo() {
List<String> list = new ArrayList<String>();
list.add("foo");
return list;
}
Related: Java generics: Collections.max () signature and comparator
+5
... ArrayList , ,
ArrayList <Supertype> obj = new ArrayList <Supertype> ();
, , ( , ).
public getAnimals(List< ? extends Animal> obj){
obj.add(something); //not allowed
}
, , .. (). classCastException .
That is why this is not allowed in this case. read Josh Bloch's Effective Java. he explained it well with the consumer goods industry analogy (PECS)
0