Feeds:
Posts
Comments

Posts Tagged ‘Generics’

Since I started my new job as a Java Software Engineer, I’ve been doing some training in the form of reading Effective Java by Joshua Bloch. Today I came across the rather baffling method signature below: –

Public static <T extends Comparable<? Super T>> T max(List<? Extends T> list)

“OMG… What is that all about?” I thought at first glance. The description informs me that the method max takes a list of any comparable type and returns the object with the maximum value as defined by the implementation of the Comparable interface’s compareTo method.

So what’s with all the bloat? The answer is that generics are invariant rather than covariant in Java. For example List<String> is not a subclass of List<Object>. In order to make your generic methods as flexible as possible it is necessary to support the inheritance of parameter types, which can cause quite a headache. I think I’ve just about got my head round this example so I will do my best to explain it.

max is a method with modifiers public and static. Its return type is the generic type T.

Generic methods declare a type parameter list which goes in between the modifiers (public static) and the return type (T). The type parameter for max is  T extends Comparable<? Super T>>. This means that T is type that is comparable with itself or its super class.

To break this down, let’s consider the simpler parameter type T extends Comparable<T>>. In this example, T is the type that is comparable with itself only. Adding the bounded wildcard type <? Super T> allows T to be comparable with its super types as well. This is necessary if we apply T as a class that subclasses a class E that implements Comparable<E>. One example of this that the book gives is the java.util.concurrent.ScheduledFuture interface which is a sub-interface of java.util.concurrentDelayed. Delayed extends Comparable<Delayed> whereas ScheduledFuture does not extend the Comparable interface directly.

The final brain teaser is the sole parameter list of type List<? Extends T>. This means that list can be a List of any type that is a subclass of T (remember everything is a subclass of itself).

Phew, I hope this made some sense. Please appreciate I’m hardly an expert in this field, so if you spot an error in my description then let me know!

Advertisements

Read Full Post »