This works to return a list of ints:
public List<Integer> GetIListImpl() {
return new ArrayList<Integer>();
}
But what if I want to let the caller specify the generic type? Something like this, although syntactically I’m not sure how to do it:
public List<T> GetIListImpl<T>() {
return new ArrayList<T>();
}
The usage would be:
List<String> = GetIListImpl<String>();
On generic
staticfactory methods for parameterized typesIt looks like you want to write convenient factory methods to instantiate generic collections.
You can write generic methods like these:
Then you can simply write:
Note that in some contexts, the above methods do not have to be
static, and you may opt to leave out the implementationclassnames out of the methods and only use theinterfacenames (e.g.newList,newMap).An endorsement from Effective Java 2nd Edition
This kind of generic type-inferring
staticfactory method is actually endorsed by Effective Java 2nd Edition; it had the unique privilege of being the very first item discussed in the book.Here are the relevant quotes from Item 1: Consider
staticfactory methods instead of constructors:The item also prescribes the common naming convention for these
staticfactory methods:On explicit type parameters
You do not have to explicitly provide the type parameters in most cases, since the Java generics type inference system can usually figure out what you need.
Nevertheless, to provide explicit type parameters, the syntax is to put it before the method name (not after). Here’s an example of invoking with explicit parameter the generic method
<T> List<T> emptyList()fromjava.util.Collections:Note that a syntax quirk of the explicit type parameterization for generic method invocation is that you must qualify the type (if
static) or the object that you’re invoking the method on, even if they can be omitted if it was not an explicit parameterization.References
Appendix: Collection factory methods from Guava
It should be noted that Guava in fact already provides the
staticfactory methods for the types in Java Collections Framework:From the main
package com.google.common.collect:Lists.newArrayList(),newLinkedList(), …Sets.newHashSet(),newTreeSet(),newEnumSet(…), …Maps.newHashMap(),newTreeMap(),newEnumMap(…), …In fact, in the spirit of Effective Java 2nd Edition recommendation, Guava’s own collections do not provide
publicconstructors, but instead providestatic create()factory methods:HashMultiSet.create(), aMultisetimplementationTreeMultimap.create(), aMultimapimplementationThe rest of the library also provides many highly useful functionality.