Reputation: 467
What is the difference between List<Integer>
and List<? super Integer>
.
Which one is a good practice or When we should use what ?
Upvotes: 5
Views: 3769
Reputation: 122439
The most obvious difference is that you can get elements out of List<Integer>
as type Integer
, but when you get elements out of List<? super Integer>
, you can only get type Object
.
Upvotes: 1
Reputation: 89169
List<Integer>
is a List
that is bounded to a type Integer
. This means that it can receive and produce Integer
.
List<? super Integer>
is a unbounded List
that accepts any value that is a Integer
or a superclass of Integer
.
The 2nd option is best used on the PECS Principle (PECS stands for Producer Extends, Consumer super). This is useful if you want to add items based on a type T
irrespective of it's actual type.
For more information, see a related post here.
Upvotes: 5
Reputation: 17463
List<Integer>
is the best option here.
List<? super AbstractObject>
would be better option if you are dealing with polymorphism.
Upvotes: 0