Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signature of Collections.min/max method

In Java, the Collections class contains the following method:

public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> c)

Its signature is well-known for its advanced use of generics, so much that it is mentioned in the Java in a Nutshell book and in the official Sun Generics Tutorial.

However, I could not find a convincing answer to the following question:

Why is the formal parameter of type Collection<? extends T>, rather than Collection<T>? What's the added benefit?

like image 375
Marco Avatar asked May 25 '10 18:05

Marco


People also ask

What is signature of method?

The method signature in java is defined as the structure of the method that is designed by the programmer. The method signature is the combination of the method name and the parameter list. The method signature depicts the behavior of the method i.e types of values of the method, return type of the method, etc.

What is Collections max?

The max() method of java. util. Collections class is used to return the maximum element of the given collection, according to the natural ordering of its elements.


1 Answers

Type inference is a tricky topic that I'll admit that I don't know that much about. However, examine this example:

public class ScratchPad {
   private static class A implements Comparable<A> {
     public int compareTo(A o) { return 0; }
   }
   private static class B extends A {}
   private static class C extends B {}

   public static void main(String[] args)
   {
     Collection<C> coll = null;
     B b = Scratchpad.<B>min(coll);
   }

   public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> c)  {
     return null;
   }

   //public static <T extends Object & Comparable<? super T>> T min(Collection<T> c) {
   //  return null;
   //}
}

Consider that the first signature of min() allows the call to compile whereas the second does not. This isn't a very practical example, since one must ask why I would be explicitly typing the method to <B>, but perhaps there is an implicit inference where B would be the inferred type.

like image 56
Mark Peters Avatar answered Sep 29 '22 10:09

Mark Peters