-1

For example, using it when using a generic Comparator - Comparator<? super T> c

I understand that it basically means that the Comparator will compare T and its super classes, I don't however understand the logic behind it. Why not use "? extends T" ? Or, for example, I have found a similar question of someone who asked about "List<? super Number>" - does it mean that the list is gonna receive Number objects and its super classes? but Number's superclass is Object, does that mean the list can receive any Object?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Django Freeman
  • 81
  • 1
  • 2
  • 9
  • there may be a good question in here somewhere but it isn't narrowed down yet and from how this is posed it's not apparent you've read up on the linked question. If you can check out the linked question, then make a specific example with more code, then that might work out better. – Nathan Hughes Jan 16 '16 at 18:42

1 Answers1

-1

It doesn't mean T and its super-classes. It means T and its sub-classes. So no, the list cannot receive any Object, it can receive any sub-class of Number.

List<? super Number> numbers = new ArrayList<>();
Integer i = 23;
Double d = 3.14;
Object o = new Object();
numbers.add(i);
numbers.add(d);
numbers.add(o); // compilation error

Integer and Double both extend Number. They are sub-classes of Number. So they can be added to the list of numbers.

Number is a sub-class of Object. If you look at the source code, it does not explicitly extend anything (although it does implement Serializable). That means that its super-class is Object. We cannot add an Object to the numbers list.

Object o2 = 300;
numbers.add(o2);    // compilation error
numbers.add((Number) o2);   // no compilation error once we cast it

In fact, we can add an Object if it is a Number. Of course, all Numbers are Objects, although not all Objects are Numbers. However, if it was declared as an Object, then we will first have to cast it to a Number.

whistling_marmot
  • 3,561
  • 3
  • 25
  • 39
  • Can you add code example which will show what you mean? For now either your answer is unclear (at least for me) or wrong. – Pshemo Jan 16 '16 at 18:24
  • Sorry, that should have been 'it can receive any sub-class of Number' not 'it can receive any sub-class of List'. – whistling_marmot Jan 16 '16 at 18:27
  • Can you clarify what you mean by "receive" here? Really, short compilable and executable example would be nice here. – Pshemo Jan 16 '16 at 18:30