Tech and Media Labs
This site uses cookies to improve the user experience.




Java Generic Methods

Jakob Jenkov
Last update: 2014-06-23

It is possible to generify methods in Java. Here is an example:

public static <T> T addAndReturn(T element, Collection<T> collection){
    collection.add(element);
    return element;
}

This method specifies a type T which is used both as type for the element parameter and the generic type of the Collection. Notice how it is now possible to add elements to the collection. This was not possible if you had used a wildcard in the Collection parameter definition.

So, how does the compiler know the type of T?

The answer is, that the compiler infers this from your use of the method. For instance:

String stringElement = "stringElement";
List<String> stringList = new ArrayList<String>();

String theElement = addAndReturn(stringElement, stringList);    


Integer integerElement = new Integer(123);
List<Integer> integerList = new ArrayList<Integer>();

Integer theElement = addAndReturn(integerElement, integerList);    

Notice how we can call the addAndReturn() method using both String's and Integer's and their corresponding collections. The compiler knows from the type of the T parameter and collection<T> parameter definitions, that the type is to be taken from these parameters at call time (use time).

The compiler can even perform more advanced type inference. For instance, the following call is also legal:

String stringElement = "stringElement";
List<Object> objectList = new ArrayList<Object>();

Object theElement = addAndReturn(stringElement, objectList);    

In this case we are using two different types for T: String and Object. The compiler then uses the most specific type argument that makes the method call type correct. In this case it infers T to be Object.

The inverse is not legal though:

Object objectElement = new Object();
List<String> stringList = new ArrayList<String>();

Object theElement = addAndReturn(objectElement, stringList);

In this case the compiler infers, that for the method call to be type safe, T must be a String. The objectElement passed in for the T element parameter must then also be a String (and it isn't). Therefore the compiler will report an error.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC