Lists. newArrayList vs New Arraylist
What Is the Best Construction for Creating a List of Strings? Is It Lists. newArrayList() (From Guava) or New Arraylist()? Is It Just a Personal Preference? or...
What is the best construction for creating a List of Strings? Is it Lists.newArrayList() (from guava) or new ArrayList()?
is it just a personal preference?
or is it just Type generic type inference?
or is there any theoretical or practical value in using Lists.newArrayList()?
8 Answers
The guava builder saves typing the type arguments multiple times. Compare:
List<Foo<Bar, Baz>> list = Lists.newArrayList();
List<Foo<Bar, Baz>> list = new ArrayList<Foo<Bar, Baz>>();
In Java 7 it's a bit obsolete though, because you have the diamond operator:
List<Foo<Bar, Baz>> list = new ArrayList<>();
From Guava's source:
public static <E> ArrayList<E> newArrayList() {
return new ArrayList<E>();
}
All that's doing is allowing for type inference - no difference at runtime.
Add one point, overloading version of Lists.newArrayList() is more useful:
Lists.newArrayList(E... elements)Lists.newArrayList(Iterable<? extends E> elements)Lists.newArrayList(Iterator<? extends E> elements)
provide more useful functions than new ArrayList().
For example: new ArrayList() cannot do:
Lists.newArrayList("a","b");
Lists.newArrayList(anIterable);
This is what Lists.newArrayList does:
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList() {
return new ArrayList<E>();
}
So these two are basically the same, with using newArrayList having the advantage on not having to duplicate the generic type. This is very helpful on complex generics:
List<Map<X,List<Y>> list = new ArrayList<Map<X,List<Y>>();
List<Map<X,List<Y>> list = Lists.newArrayList();
As explained here, the main motivations for using Lists, Sets etc are to improve the readability/duplication in your code, and for the type inference.
Java 8 approach for overloaded constructors.
If you would like to use the overloaded constructors from Guava, I would recommend another way using Java 8 Stream Builder.
List<String> listTest = Stream.<String>builder
.add("Hello").add("My Name").add("Blah")
.build().collect(Collectors.toList());
If you are on a Java version 9+, you can use below. But this method returns an ImmutableList so you can't add more elements to it.
List.of("My","Name", "IS", "this");
As noted, Java 7 makes this obsolete, but I use the factory method because it makes changing the type of a list, set, map or whatever easier later.
You can use Arrays.asList() from java.util so you don't have to use Guava:
List<String> list = Arrays.asList("one","another", null, "one_more")
(btw, Stream Builder from Java 8, is also an option, but it's too verbose and overkill for most common use cases)