5

What is the difference between List<Integer> and List<? super Integer> .

Which one is a good practice or When we should use what ?

Marco Forberg
  • 2,634
  • 5
  • 22
  • 33
Amby
  • 447
  • 1
  • 8
  • 14

3 Answers3

5

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.

Community
  • 1
  • 1
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
0

List<Integer> is the best option here.

List<? super AbstractObject> would be better option if you are dealing with polymorphism.

Makky
  • 17,117
  • 17
  • 63
  • 86
0

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.

newacct
  • 119,665
  • 29
  • 163
  • 224