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?

2
  • 6
    Your second case will not compile. You probably mean public static <T> void myFunction(List<T> list); (<T> was placed before return type). Commented Jun 22, 2015 at 20:27
  • Here is the official tutorial about generics. The relevant items are "generic methods" and "wildcards". Commented Jun 22, 2015 at 20:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

You should use backticks ( ` ) when writing out generics, or else the site will treat them as unrecognized/unallowed HTML tags and strip them out.
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).
you are right, I intended to refer to the compiler :). thanks again.
What is the meaning of writing <T> before void ?
@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: docs.oracle.com/javase/tutorial/java/generics

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.