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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With