Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array to List or List to Array, which conversion is faster?

In java, basically these two conversions are so common and popular...

  • Array to List

    List<String> list = Arrays.asList(array);

  • List to Array

    String[] array = list.toArray(new String[list.size()]);

So the question is, which is faster, Array to List or its reverse?

Now, Why am I asking this question? Because I've to implement a method in which an array or a list, both can be passed in parameter. I just have to iterate this list and that's all. So here I have to decide that what should I convert? array to list or list to array!

like image 589
Khan Avatar asked Dec 03 '22 20:12

Khan


2 Answers

Arrays.asList is faster because it does not copy data - it returns an object wrapping the array passed to it, and implementing the List interface. Collection.toArray() copies the data to the array, so it runs in O(N) instead of O(1).

like image 144
yole Avatar answered Feb 11 '23 22:02

yole


Arrays.asList will faster since it doesnt have to copy any data instead it has to just pack it.

like image 30
spandey Avatar answered Feb 11 '23 23:02

spandey