2 years ago

#50336

test-img

Ahmad Alhaj-Karim

Why lower bound(<? super T>) is mutable and upper bound not (<? extends T>) in Java

I'm trying to understand Java Generic so I ended up with not able to understand why lower bound type can be mutable and upper bound types not.

The example I have:

List<? extends String> upperBounded = new ArrayList();.
List<? super String> lowerBounded = new ArrayList();

upperBounded.add("A"); // Does not compile (capture of ? extends String)
lowerBounded.add("A"); // Compile just fine

So could someone explain me the reason that upper bounded types can not be mutable and lower bounded types can be?

Thank you!

java

generics

immutability

mutable

0 Answers

Your Answer

Accepted video resources