Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one is more efficient of using array list?

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"));
like image 237
Rajesh Avatar asked Jan 28 '16 14:01

Rajesh


1 Answers

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.

like image 127
Jon Skeet Avatar answered Sep 28 '22 08:09

Jon Skeet