3

I can addAll array elements in to ArrayList by following two ways,

First,

List<String> list1 = new ArrayList<String>();
list1.addAll(Arrays.asList("23,45,56,78".split(",")));
System.out.println(list1);

Second,

List<String> list2 = new ArrayList<String>();
list2.addAll(new ArrayList<String>(Arrays.asList("23,45,56,78".split(","))));
System.out.println(list2);

Both works fine. And my question is Is there any difference between these two. And which one can be used for better practice Why ?

Mureinik
315k54 gold badges390 silver badges403 bronze badges
asked Jan 27, 2014 at 18:15
0

3 Answers 3

5

Both approaches produce the same result, so in that respect they are equivalent.

The second one, however, is wasteful. Arrays.asList does not allocate additional memory - it just wraps a given array in a List-like API. Creating a new ArrayList, on the other hand, allocates, albeit temporarily, another array with the same size, and copies all the values from the source array to the internal array of the ArrayList's implementation.

With small arrays it's doubtful you'd even notice the difference, but the first approach is definitely more efficient.

answered Jan 27, 2014 at 18:19

Comments

2

The addAll method is defined on the Collection interface. With both examples, you are passing in a List. You aren't keeping the ArrayList you're creating in the second example, but it's not even necessary. Arrays.asList sends the List just fine into addAll by itself. The creation of the unnecessary ArrayList in the second example is unnecessary, so the first example is preferred.

answered Jan 27, 2014 at 18:19

Comments

2

Of the two you listed, the first is better. The second example creates another ArrayList object that isn't needed. Both would be functionally the same, but the first is more efficient.

As to the best practice, you can do this kind of thing in 1 line, not 2.

List<String> list2 = new ArrayList<String>(Arrays.asList("23,45,56,78".split(",")));

You can create a list by passing the arguments into it's constructor, a little cleaner than calling .addAll after creating the Object

answered Jan 27, 2014 at 18:20

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.