Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Why use of bounded wildcards in this example?

Tags:

java

generics

I'm taking a practice exam for one of my classes, I came across a problem that asked me to implement a static generic method. I was correct for the body of the method, but my guess for the actual method signature was different.

I guessed:

public static <T> boolean isSorted(T[] array, Comparator<T> cmp){ ...

The practice exam's answer, however, used a bounded wildcard like this:

public static <T> boolean isSorted(T[] a, Comparator<? super T> cmp)

I read through the javadoc again and even though I know what this means (super being restrictive in a upwardly inclusive manner in the class hierarchy for that type T you specify), I don't think I fully understand why you would want to use a bounded wildcard in like this.

Thanks in advance.

like image 284
Paul Nelson Baker Avatar asked Jun 05 '14 07:06

Paul Nelson Baker


1 Answers

In Java, subclasses ought to behave like base classes and possibly extend behavior - using your proposed signature, an array of Integer for example could only be checked against a Comparator working on Integer only and not by a Comparator working on Number, for example. This lower bound only broadens the possible use cases for the method as it extends the number of possible Comparator objects for re-use.

like image 140
Smutje Avatar answered Oct 10 '22 09:10

Smutje