Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an object to a generic ArrayList in Java [duplicate]

Tags:

java

generics

Why this code does not compile (Parent is an interface)?

List<? extends Parent> list = ...
Parent p = factory.get();   // returns concrete implementation
list.set(0, p);   // fails here: set(int, ? extends Parent) cannot be applied to (int, Parent)
like image 938
Sergey Mikhanov Avatar asked May 24 '26 23:05

Sergey Mikhanov


2 Answers

It's doing that for the sake of safety. Imagine if it worked:

List<Child> childList = new ArrayList<Child>();
childList.add(new Child());

List<? extends Parent> parentList = childList;
parentList.set(0, new Parent());

Child child = childList.get(0); // No! It's not a child! Type safety is broken...

The meaning of List<? extends Parent> is "The is a list of some type which extends Parent. We don't know which type - it could be a List<Parent>, a List<Child>, or a List<GrandChild>." That makes it safe to fetch any items out of the List<T> API and convert from T to Parent, but it's not safe to call in to the List<T> API converting from Parent to T... because that conversion may be invalid.

like image 69
Jon Skeet Avatar answered May 26 '26 12:05

Jon Skeet


List<? super Parent>

PECS - "Producer - Extends, Consumer - Super". Your List is a consumer of Parent objects.

like image 31
Bozho Avatar answered May 26 '26 13:05

Bozho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!