Reputation: 4211
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!
Upvotes: 5
Views: 4034
Reputation: 1112
Arrays.asList will faster since it doesnt have to copy any data instead it has to just pack it.
Upvotes: 1
Reputation: 148910
IMHO, you are handling the rod the wrong side. The good question to ask is whether you need an array or List in your method. By the way, List
it just an interface, and many implementations could exist. For example the JDK directly provides ArrayList
which is backed by an array, so conversion to array should be fast, and LinkedList
which is a doubly linked implementation, and many others including abstract classes intended to help for custom implementations.
In short, you know how you want to use the elements in your method, so just use the more appropriate container.
In my opininion, if you intend to iterate the elements, use a List
, if you need intensive random access and could receive an linked list implementation, then use an Array.
Upvotes: 0
Reputation: 97168
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).
Upvotes: 17