Where can we use ArrayList <? extends My_Class>

Where we can ArrayList<? extends My_Class>, because it will not allow you to add any new item if you declare it as follows:

ArrayList<? extends My_Class> obj=new ArrayList<? extends My_Class>();
list.add(new Derived_My_Class()); //this is compilation error
+5
source share
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
source

, ArrayList , : , .

My_Class ArrayList<My_Class>; My_Class DerivedClass .

+2

... 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
source

All Articles