3

Currently, I'm learning java generics. I have question related to Collections.addAll()

public static <T> boolean addAll(Collection<? super T> c, T... elements) {
  boolean result = false;
  for (T element : elements)
    result |= c.add(element);
  return result;
}

Why do we use lower bounded wildcard? can't we remove it?

public static <T> boolean addAll(Collection<T> c, T... elements) {
  boolean result = false;
  for (T element : elements)
    result |= c.add(element);
  return result;
}

What is the affect of replacing Collection<? super T> with Collection<T> in this case?

Anthony J.
  • 375
  • 1
  • 5
  • 14
  • We can't remove it! A very illuminating contribution to the topic can be found [here](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super). – Kaplan Nov 12 '19 at 12:48

1 Answers1

1

Collection<? super T> allows you call the method on a Collection that contains elements of any supertype of T. So if you have a bunch of objects of the WholeNumber class and you want to add them to a variable of type Collection<WholeNumber>, both would work. But if you have a Collection<RealNumber>, you wouldn't be able to do the second addAll method, since RealNumber and WholeNumber are different, even though it makes sense to a person that a WholeNumber can be part of a list of RealNumbers. Since Java is invariant, the first ? super T allows more flexibility, without you having to typecast things.

HTNW
  • 27,182
  • 1
  • 32
  • 60
user
  • 7,435
  • 3
  • 14
  • 44
  • 2
    Please use backticks to format code, in the future. The `<>`s used for Java generics got confused with HTML tags and made your answer appear wrong until I used backticks to fix it. – HTNW Nov 12 '19 at 20:38