I prefer to use static factory methods of the following form:
public final class CollectionUtils { private CollectionUtils() { } public static <T> List<T> list(T... data) { return Arrays.asList(data); } public static <T> ArrayList<T> newArrayList() { return new ArrayList<T>(); } public static <T> ArrayList<T> newArrayList(T... data) { return new ArrayList<T>(list(data)); } }
So you can use them in your code as follows:
import static CollectionUtils.list; import static CollectionUtils.newArrayList; public class Main { private final List<String> l1 = list("a", "b", "c"); private final List<String> l2 = newArrayList("a", "b", "c"); }
This way you get a relatively compact way to create and populate lists and should not duplicate generic ads. Note that the list method simply creates a list view of the array. You cannot add items to it later (or delete). Meanwhile, newArrayList creates a regular ArrayList object.
As Joachim Sauer noted, these utility methods (and many other useful things) can be found in the Google Collections Library (which is now part of the Guava project).
Rorick
source share