I know generics but I am not clear on this syntax. For instance, in Collections.sort() :
public static <T> void sort(List<T> list, Comparator<? super T> c)
What is the significance of static <T>
before return type void ?
I know generics but I am not clear on this syntax. For instance, in Collections.sort() :
public static <T> void sort(List<T> list, Comparator<? super T> c)
What is the significance of static <T>
before return type void ?
The method signature from sort
:
public static <T> void sort(List<T> list, Comparator<? super T> c) {
This <T>
defines an arbitrary generic type T that can be referenced in the method definition.
What we are saying here is that the method requires a List
of some type (we don't care which) T and a Comparator
of another type but this type must be a supertype of T. This means that we can do this:
Collections.sort(new ArrayList<String>(), new Comparator<String>());
Collections.sort(new ArrayList<Integer>(), new Comparator<Number>());
But not this
Collections.sort(new ArrayList<String>(), new Comparator<Integer>());
What is the significance of static
<T>
before return type void ?
This is a generic method, and <T>
is its type parameter. It says that it will sort a list containing objects of any type (List<T>
) as long as the comparator is able to compare objects of this type or any of its supertypes (Comparator<? super T>
). Thus the compiler will allow you to call sort
passing, for example, a List<Integer>
and a Comparator<Number>
(as Integer
is a subtype of Number
), but not a List<Object>
and a Comparator<String>
.
You can sort without instantiating Collections
. The sort()
method is a static method of Collections
class.
Consider the difference in syntax between:
Collections col = new Collections();
col.sort(someCollection);
and
Collections.sort(someCollection);
The sort()
method doesn't have to rely on properties of some possible Collections object. It is therefore better to declare is as a static
method as a matter of design.
The <T>
is called type parameter which is here used to abstract over the type of items the sort method is operating on. You can have type parameters for class or method. This is the syntax for specifying the type parameter for a method which must be before the return type of the method.