Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can we use ArrayList< ? extends My_Class>

Tags:

java

generics

Where can we ArrayList<? extends My_Class> because it won't allow you to add any new element if you declare it of this way:

ArrayList<? extends My_Class> obj=new ArrayList<? extends My_Class>();
list.add(new Derived_My_Class()); //this is compilation error
like image 816
user1554627 Avatar asked Jul 26 '12 12:07

user1554627


2 Answers

You are correct, your ArrayList cannot be used the way it is derived: there is nothing that you can put into it.

What you want for storing My_Class and its subclasses is simply ArrayList<My_Class>; it will take objects of My_Class and all its DerivedClass correctly.

like image 29
Sergey Kalinichenko Avatar answered Oct 14 '22 10:10

Sergey Kalinichenko


The widely-used acronym for describing these keywords is: PECS: Producer extends - consumer super.

So, if you use "extends" your collection produces elements of the given type. So you can't add to it, you can only take from it.

An example usage would be to provide a client of your API with a list:

public List<? extends CharSequence> getFoo() {
    List<String> list = new ArrayList<String>();
    list.add("foo");
    return list;
}

Related: Java generics: Collections.max() signature and Comparator

like image 146
Bozho Avatar answered Oct 14 '22 12:10

Bozho