简体   繁体   中英

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

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM