I was wondering, which way of initialization of a list is better?
public class Main {
private final List<String> l = new ArrayList<String>();
{
l.add("a");
l.add("b");
l.add("c");
}
}
public class Main {
private final List<String> l = new ArrayList<String>() {{
l.add("a");
l.add("b");
l.add("c");
}};
}
the former, since it doesn't create an anonymous class; check the reasons here
Neither, because none is making the list immutable. I guess you want to make it immutable, when you use final
. If thats not the case, I apologize for my assumption.
If I am correct in assuming that, you should have a look into Collections.unmodifiableList()
. And the latter will come handy,
private final List<String> l = Collections.unmodifiableList(new ArrayList<String>() {{
add("a");
add("b");
add("c");
}});
Otherwise, dfa is correct in suggesting the former.
Another way can be this,
private final List<String> l = Collections.unmodifiableList(Arrays.asList("a",
"b", "c"));
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With