0

Considering the two functions:

public static void myFunction(List<?> list);

public static <T> void myFunction(List<T> list);

Please explain why we have included <T> before myFuction, and what does it signify?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Prateek Joshi
  • 3,929
  • 3
  • 41
  • 51
  • 6
    Your second case will not compile. You probably mean `public static void myFunction(List list);` (`` was placed before return type). – Pshemo Jun 22 '15 at 20:27
  • Here is the [official tutorial about generics](https://docs.oracle.com/javase/tutorial/java/generics/index.html). The relevant items are "generic methods" and "wildcards". – RealSkeptic Jun 22 '15 at 20:31

1 Answers1

1
  1. When you use <?> you are telling the virtual machine that you don't know what type of object will be in the List, could one type could be more than one type. List<?> is the equivalent of List from previous 1.4 Java version when you could add to a list any type of object and there was no constraint on that.

  2. When you use <T> you are defining a generic method. You are telling the compiler that the List<T> is a list of objet of type T, which will determined from the call to the method, but you enforce that all object from List are of the same type, T. You include <T> before the the function name to specify that you are defining a generic method, and the compiler to know that T should be treated as a type and not as variable.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
iullianr
  • 1,274
  • 10
  • 11
  • You should use backticks ( ` ) when writing out generics, or else the site will treat them as unrecognized/unallowed HTML tags and strip them out. – yshavit Jun 22 '15 at 20:31
  • Np! And while I'm here, a small nit: in neither case do you tell the virtual machine anything -- all of that info is erased by the time the JVM runs. You're giving the information to the Java-to-bytecode compiler (javac or equivalent). – yshavit Jun 22 '15 at 20:33
  • you are right, I intended to refer to the compiler :). thanks again. – iullianr Jun 22 '15 at 20:39
  • What is the meaning of writing before void ? – Prateek Joshi Jun 22 '15 at 21:06
  • @PrateekJoshi It just declares that `T` is the name of a generic parameter. You can think of it as "for some type T". If you haven't read the generics tutorial, I would recommend it: https://docs.oracle.com/javase/tutorial/java/generics/ – yshavit Jun 22 '15 at 21:16