81

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()?

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
asela38
  • 4,546
  • 6
  • 25
  • 31
  • 6
    You should read [the section about static constructors](http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained) – assylias Apr 02 '12 at 17:32

8 Answers8

102

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<>();
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 39
    It's not quite obsolete, due to the overloads -- `Lists.newArrayList(1, 2, 3)` lets you initialize with elements, and `Lists.newArrayListWithExpectedSize(20)` makes the meaning of `20` more obvious than `new ArrayList<>(20)`. The "official answer" to this question, by the way, is [here](http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Static_constructors). – Louis Wasserman Apr 02 '12 at 17:47
  • 14
    Yeah, but it's another method. I meant the no-arg one is obsolete. – Bozho Apr 03 '12 at 05:42
  • 4
    For what it's worth, it also frees the call site from having to import `ArrayList`. – Paul Bellora Apr 05 '12 at 15:57
  • 2
    I always use just List> list = new ArrayList(); – Ondra Žižka Jul 10 '13 at 03:59
  • 11
    @PaulBellora But instead creates an static import on Guavas Lists (so no reduce of imports, nor having lost the transitive dependency on ArrayList, if that was your goal). – Dag Dec 16 '13 at 12:00
  • 1
    I recently came across your [blog post](http://techblog.bozho.net/pretty-print-spring-mvc-json-per-request/) where this `List.newArrayList` is used where it simplifies the code very much. But what is the alternative for those who don't have Guava library? – Lucky May 20 '16 at 11:15
  • The information @LouisWasserman mentioned is now here https://github.com/google/guava/wiki/CollectionUtilitiesExplained#static-constructors – wax Mar 30 '18 at 15:49
  • @LouisWasserman actually, `Lists.newArrayListWithExpectedSize(20)` is far from being “more obvious than `new ArrayList<>(20)`”, as contrary to the latter, the resulting list will *not* have a capacity of `20`. It couldn’t be less obvious. Besides that, `Arrays.asList(1, 2, 3)` worked even before Guava existed. And if you truly need an `ArrayList`, you can use `new ArrayList<>(Arrays.asList(1, 2, 3))` and even `Lists.newArrayList(E...)`’s documentation itself acknowledges that the tiny syntactic sugar does not justify this method at all and suggests its future removal. – Holger Aug 23 '19 at 12:03
31

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
  • Well, there are 2 performance impacts from bytecode perspective: - for sure, an additional `invokestatic` - guava classes might be generated with an older/less optimal bytecode version than what the running JVM supports – rdesgroppes Sep 24 '22 at 10:26
15

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);
卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130
4

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();
phlogratos
  • 13,234
  • 1
  • 32
  • 37
  • The full method call with Guava according to the method signature would be `Lists.>>newArrayList()`. You you can leave out the the generics type. But you can do this with the Constructor as well: `List>> list = new ArrayList();` works as well. – Matthias Wimmer Jun 12 '16 at 16:51
3

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.

darrengorman
  • 12,952
  • 2
  • 23
  • 24
2

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");
Rituraj
  • 685
  • 6
  • 6
  • Why do you recommend this? (Also, why not `Stream.of("Hello", "My Name", "Blah")`?) – aioobe May 08 '19 at 18:11
  • @aioobe - that works too, but only if you have all the elements available to you in one line more like declaration or hardcoded values. But if you have to iterate values in order to create a new list, then Stream Builder would be a better choice. – Rituraj Jun 16 '20 at 16:11
1

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)

ritorujon
  • 61
  • 5
1

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.

daveb
  • 74,111
  • 6
  • 45
  • 51