7

Which one is more efficient to instantiate a list ?

List<Type> list = new ArrayList<Type>(2);
list.add(new Type("one"));
list.add(new Type("two"));

OR

List<Type> list = Arrays.asList(new Type("one"), new Type("two"));

1 Answer 1

14

They create different types of objects. new ArrayList<>() creates a java.util.ArrayList, which can be added to, etc.

Arrays.asList() uses a type which happens to also be called ArrayList, but is a nested type (java.util.Arrays$ArrayList) and doesn't allow elements to be added or removed. It just wraps an array.

Now, if you don't care about those differences, you end up with two roughly-equivalent implementations, both wrapping an array in the List<> interface. I would be very surprised to see them differ in performance in any significant way - but as ever, if you have specific performance concerns, you should test them in your particular context.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, I didn't even know that ArrayList from Arrays.asList() actually is another ArrayList than the java.util.ArrayList.
I didn't know that either... As it seems the 2 variants differ a bit in efficiency (at least on my machine). On 100 million runs the first variant needs ~ 1500 ms and the second ~ 900 ms

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.