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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With