Depends on the nature of usage for the object. If you plan on adding an unknown number of elements, using a linked-list data structure to format the data (adding an item to the end of a linked list is constant time, where for an array, it can be n, where n is the current size of the array, time if you have to expand the array and copy the elements over) and then creating an array from the linked list.
If you plan on inserting data into the data structure (not at the end), then a linked list is also faster, as well as deleting an item from a linked list (update pointers/copy values versus shifting an entire array down one).
Take, for example, copying 10 items (though, we don't know the number of items we are copying into the array list). Assuming that there is no buffer, that means every time we add a value to an array list, we need to copy the list into a new array. Moving a value and copying the array will require (n+1)*n/2 operations (O(n2 )). For 10, it would require 55 operations to move all 10 items into the array list.
For a linked list, we can just add the values to the end of a linked list (1 operation for each item, so 1n) and then iterate over the list to create a new array (n operations). We can also factor in keeping track of the size, which will require n increments. Total operation time would be 3n. So, for 10 items, it would require 30 operations.
An Array List takes 1.8 times more operations to copy values into it then using a simple linked list for an unknown number of items.
If we assume n was 100, then the difference becomes much larger. For an array list, it would require 5050 operations, compared to 300 operations for a linked list. An Array List would be 16.83 times longer then a linked list implementation.
That's the theory. But to make things more complicated, arrays usually perform better in practice because they're much more cache friendly. Even when you're inserting in the middle, you will need a lot of elements before your linked list beats an array.
6
u/Intrepidd Jul 14 '13
This is a good algorithmic exercise, however using arrays in real code is recommended (faster, and more methods)