Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I explicitly pass the type argument to a generic Java method?

People also ask

How do you pass a generic argument in Java?

When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char. Test<int> obj = new Test<int>(20);

What are the rules to declare generic methods in Java?

The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type.

Which reference types Cannot be generic in Java?

Almost all reference types can be generic. This includes classes, interfaces, nested (static) classes, nested interfaces, inner (non-static) classes, and local classes. The following types cannot be generic: Anonymous inner classes .

Which of these type Cannot be used to initiate a generic type?

Which of these types cannot be used to initiate a generic type? Explanation: None.


When the java compiler cannot infer the parameter type by itself for a static method, you can always pass it using the full qualified method name: Class . < Type > method();

Object list = Collections.<String> emptyList();

You can, if you pass in the type as a method parameter.

static <T> List<T> createEmptyList( Class<T> type ) {
  return new ArrayList<T>();
}

@Test
public void createStringList() {
  List<String> stringList = createEmptyList( String.class );
}

Methods cannot be genericised in the same way that a type can, so the only option for a method with a dynamically-typed generic return type -- phew that's a mouthful :-) -- is to pass in the type as an argument.

For a truly excellent FAQ on Java generics, see Angelika Langer's generics FAQ.

.
.

Follow-up:

It wouldn't make sense in this context to use the array argument as in Collection.toArray( T[] ). The only reason an array is used there is because the same (pre-allocated) array is used to contain the results (if the array is large enough to fit them all in). This saves on allocating a new array at run-time all the time.

However, for the purposes of education, if you did want to use the array typing, the syntax is very similar:

static <T> List<T> createEmptyList( T[] array ) {
  return new ArrayList<T>();
}

@Test
public void testThing() {
  List<Integer> integerList = createEmptyList( new Integer[ 1 ] );
}