Java-syntax for explicitly specifying generic arguments in method calls

JavaGenerics

Java Problem Overview


What is the syntax for explicitly giving the type parameters for a generic Java method?

Java Solutions


Solution 1 - Java

According to the Java specification that would be for example:

Collections.<String>unmodifiableSet()

(Sorry for asking and answering my own question - I was just looking this up for the third time. :-)

Solution 2 - Java

The following is not the syntax

<ArgType>genericMethod()

It seems the type arguments must come after a dot as in

SomeClass.<ArgType>genericMethod()
this.<ArgType>genericMethod()
p.<ArgType>genericMethod()
super.<ArgType>genericMethod()
SomeClass.super.<ArgType>genericMethod()
SomeClass.this.<ArgType>genericMethod()

Solution 3 - Java

A good example from java.util.Collection of specifying a generic method which defines its own generic type is Collection.toArray where the method signature looks like:

<T> T[] toArray(T[] a);

This declares a generic type T, which is defined on method call by the parameter T[] a and returns an array of T's. So the same instance could call the toArray method in a generic fashion:

Collection<Integer> collection = new ArrayList<Integer>();
collection.add(1);
collection.add(2);

// Call generic method returning Integer[]
Integer[] ints = collection.toArray(new Integer[]{});

// Call generic method again, this time returning an Number[] (Integer extends Number)
Number[] nums = collection.toArray(new Number[]{});

Also, see the java tutorial on generic type parameters.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHans-Peter St&#246;rrView Question on Stackoverflow
Solution 1 - JavaHans-Peter StörrView Answer on Stackoverflow
Solution 2 - JavaTheodore NorvellView Answer on Stackoverflow
Solution 3 - JavakrockView Answer on Stackoverflow