Which way to initialize a list is better

I was wondering which way to initialize 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"); }}; } 

+7
java
source share
3 answers

the first, because it does not create an anonymous class; check the reasons here

+4
source share

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).

+6
source share

Not because no one makes the list immutable. I think you want to make it immutable when using final . If this is not the case, I apologize for my assumption.

If I understood correctly, you should take a look at Collections.unmodifiableList() . And the last come in handy

 private final List<String> l = Collections.unmodifiableList(new ArrayList<String>() {{ add("a"); add("b"); add("c"); }}); 

Otherwise, dfa is correct under the assumption of the first.

Another way could be this,

 private final List<String> l = Collections.unmodifiableList(Arrays.asList("a", "b", "c")); 
+2
source share

All Articles