Rakesh KR
Rakesh KR

Reputation: 6527

Adding Arrays in to ArrayList

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 ?

Upvotes: 3

Views: 135

Answers (3)

Durandal
Durandal

Reputation: 5663

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

Upvotes: 2

Mureinik
Mureinik

Reputation: 311326

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.

Upvotes: 5

rgettman
rgettman

Reputation: 178263

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.

Upvotes: 2

Related Questions