5

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.

Sajan Chandran
  • 10,929
  • 3
  • 26
  • 37
Paul FREAKN Baker
  • 3,755
  • 8
  • 39
  • 79
  • 1
    Have a look at this post: http://stackoverflow.com/questions/1292109/generics-get-and-put-rule. And then learn about PECS (producer extends consumer super). – Seelenvirtuose Jun 05 '14 at 08:21

1 Answers1

7

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.

Smutje
  • 16,951
  • 4
  • 21
  • 38
  • Another way to say this would be "If I have a comparator able to sort any Number, I certainly should be able to compare Integers, so it should be a valid second argument to isSorted". – Michael Anderson Jun 05 '14 at 08:11
  • That took me a little while to wrap my head around, but that makes perfect sense. Thanks for clarifying that for me! – Paul FREAKN Baker Jun 05 '14 at 09:29
  • "only and not by a Comparator working on Number" although in this case it would, because an array of Integer *is* an array of Number. – newacct Jun 05 '14 at 20:37