Search code examples
javaarraylist

Java - new ArrayList(List) vs empty ArrayList() + add(element)


I've learned today that you can create a new ArrayList object utilizing a static method like so:

List<String> listDummy = Arrays.asList("Coding", "is", "fun"); 
ArrayList<String> stringList = new ArrayList<>(listDummy);

Or even more concisely:

ArrayList<String> stringList = new ArrayList<>(Arrays.asList("Coding", "is", "fun"));

How expensive is this performance-wise compared to the "traditional" way?

ArrayList<String> stringList = new ArrayList<>();
stringList.add("Coding");
stringList.add("is");
stringList.add("fun");

I realize the upper way of creating an ArrayList includes an extra List object creation, however, I prefer the shorter and more compact syntax to an extent that I'm willing to sacrifice some performance but gotta draw the line somewhere.

PS. leaving the type information(<>) empty in "new ArrayList<>()" is a Java SE 7 feature, not an error.

Thank you beforehand for any answers!


Solution

  • The usual add() way calls three methods.

    The asList() way makes an array, then does clone() on it (which does a shallow copy), then does copy all the elements manually because of this bug. And afterwards, if you want to add another element to stringList, the array will have to be made larger and elements re-copied, because the size was exact for the elements provided. (all this is implementation dependant and assumes Oracle JDK)

    For three elements, the latter will be slower, but for any practical use, it will be negligible. For many elements, the two approaches might get equal in performance and the former one might even get slower.

    Write what you think will read the best, the performance penalty is minimal and you should not care about it until it proves itself to be bottleneck.


    All that said, if you're after consice syntax, you could like Google Guava's Lists:

    List<String> stringList = Lists.newArrayList("Coding", "is", "fun");
    

    I haven't used a classic ArrayList constructor for quite a while now.