1

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 ?

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
Ramp
  • 1,772
  • 18
  • 24
  • My question should have been clearer, I understand the 'static' part the question is on the generic . Edited the question to highlight only the generic – Ramp Feb 21 '13 at 16:35

4 Answers4

3

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>());
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
  • Relationship between List and its Comparator is established in the parameters itself when we say List and Comparator super T>. What does in question specify on top of that ? – Ramp Feb 21 '13 at 17:10
  • Nothing. But you need to declare `T` somewhere. You can do that at the top of the class and that means you have same `T` everywhere or you can do that on a method specific basis - as here. – Boris the Spider Feb 21 '13 at 17:27
2

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>.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
1

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.

ipavlic
  • 4,906
  • 10
  • 40
  • 77
1

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.

Marimuthu Madasamy
  • 13,126
  • 4
  • 30
  • 52