3

I have a query on Collections API binary search and sort method declarations. There is upper bound wildcard use with list parameter in binarySearch. But the list parameter in the sort method does not use an upper bound wildcard. Why are these different?

For sort, list does not use upper bound wildcard.

static <T> void sort(List<T> list, Comparator<? super T> c)

For binarySearch, list uses an upper bound wildcard.

static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)

I am wondering why upper bound is needed here if it is not needed in the sort method.

ordonezalex
  • 2,645
  • 1
  • 20
  • 33
Pritesh
  • 31
  • 1
  • 1
    `binarySearch()` only needs to read from the passed `List`, but the `sort()` needs to swap elements around, and thus needs to read and write from the `List` – Lino Jul 16 '20 at 07:29

1 Answers1

0

The reason for this is because when you have a List<? extends T>, you can't add elements to or remove elements from it, because you don't know the type of the elements in that list. It could be just T, it could be Object, or any superclass of T in between. See Java Generic with ArrayList<? extends A> add element for more information.

As @Lino - Vote don't say Thanks said above, this is fine with binarySearch, because it doesn't have to add or remove elements from the given list - as long as the comparator can compare each element, it's happy. However, sort does have to move elements around, so it needs the list to be of a known type.

This doesn't mean it's actually taken advantage of: java.util.Collections.java sources (OpenJDK 8)

user
  • 7,435
  • 3
  • 14
  • 44