Do these two Java generic methods accept the same data types?

Viewed 53

I'm new to Java and I'm trying to learn about generics. I tried to implement a simple version of binarySearch() method that is also found in the Collections class. I looked up the method signature and it's something like this:

public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) {
  // definition
}

I was wondering if the method above still accepts the same data types if you were to change the method definition to this:

public static <T extends Comparable<? super T>> int binarySearch(List<T> list, T key) {
  // definition
}

If not, what are the differences between the two? Thank you!

2 Answers

Consider these classes:

class A extends Comparable<A> { /* ... */ }
class B extends A { /* ... */ }

Now define a key and a list with these types:

A key = new B();
List<B> list = List.of(key);

You can invoke the first form with these arguments, but not the second.

For example:

static class NonComparable {

}

static class MyComparable implements Comparable<NonComparable> {
    @Override
    public int compareTo(NonComparable o) {
        return 0; // irrelevant for the example
    }
}

And then declare the parameters:

List<MyComparable> list = Arrays.asList(new MyComparable());
NonComparable  nonComparable = new NonComparable();
binarySearch(list, nonComparable);

One of your method definitions allows an invocation, the other does not.

Related