Which one is more efficient of using array list?
Asked Answered
L

1

6

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"));
Lutyens answered 28/1, 2016 at 14:40 Comment(0)
S
15

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.

Senn answered 28/1, 2016 at 14:50 Comment(2)
Wow, I didn't even know that ArrayList from Arrays.asList() actually is another ArrayList than the java.util.ArrayList.Withershins
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 msDieppe

© 2022 - 2025 — McMap. All rights reserved.