Alex Rivera | Logout

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

Asked 2008-08-24T12:03:28.367
33

I have defined a Java function:

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

One way to call it is like so:

List<Integer> myList = createEmptyList(); // Compiles

Why can't I call it by explicitly passing the generic type argument? :

Object myObject = createEmtpyList<Integer>(); // Doesn't compile. Why?

I get the error Illegal start of expression from the compiler.

Edit
Report

1 Answer

0

@pauldoo Yes, you are quite right. It is one of the weaknesses with the java generics imho.

I response to Cheekysoft I'd like to propose to also look at how it is done by the Java people themselves, such as T[] AbstractCollection#toArray(T[] a). I think Cheekysofts version is superior, but the Java one has the advantage of familiarity.

Edit: Added link. Re-edit: Found a bug on SO :)


Follow-up on Cheekysoft: Well, as it is a list of some type that should be returned the corresponding example should look something like:

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

But yes, passing the class object is clearly the better one. My only argument is that of familiarity, and in this exact instance it isn't worth much (in fact it is bad).

answered 2008-08-24T12:37:16.617

Your Answer