Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 654
Rakesh KR Avatar asked Sep 17 '26 06:09

Rakesh KR


2 Answers

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.

like image 149
Mureinik Avatar answered Sep 18 '26 20:09

Mureinik


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.

like image 39
rgettman Avatar answered Sep 18 '26 21:09

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!