I prefer using static factory methods of the next kind:
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 in the next way:
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");
}
Thus you get relatively compact way of creating and populating lists and don't need to duplicate generic declarations. Note, that list
method just creates list view of array. You cannot add elements to it later (or remove). Meanwhile newArrayList
creates usual ArrayList
object.
As Joachim Sauer noted, these utility methods (and many other useful things) can be found in Google Collections library (which is now a part of Guava project).