Kertes Gray

Greenhorn
+ Follow
since Aug 31, 2021
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Kertes Gray

I think the code below should cause a compiler error as well.
Referencing this code:

2: static class Sparrow extends Bird { }
3: static class Bird { }
4:
5: public static void main(String[] args) {
6: List<? extends Bird> birds = new ArrayList<Bird>();
7: birds.add(new Sparrow()); // DOES NOT COMPILE
8: birds.add(new Bird()); // DOES NOT COMPILE
9: }

My question is what is the purpose of the collection being immutable when assigned to a bounded reference(Upper-Bound),
when this code can do what it prevents:

List<Bird> birds1 = new ArrayList<>();
birds1.add(new Sparrow());
birds1.add(new Bird());
List<? extends Bird> birds2 = birds1;
//birds2.add(new Sparrow());
//birds2.add(new Bird());

(Removing the comment will cause a compiler error)
The answer is the moment you put a collection with a reference bound(upper-bound), it is now immutable.
Before you assign the collection object to a bounded reference, you should modify it head on.

List<Bird> birds1 = new ArrayList<>();
birds1.add(new Sparrow());
birds1.add(new Bird());
List<? extends Bird> birds2 = birds1;
//birds2.add(new Sparrow());
//birds2.add(new Bird());

If you remove the comment, the code will not compile.