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!
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).
Arrays.asList will faster since it doesnt have to copy any data instead it has to just pack it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With