The title says it all. I have to add several thousand objects to a List and then sort them. For now I thought (since adding something to a LinkedList is considerably faster) I'd use a LinkedList for creation and then make a new ArrayList like so:
LinkedList<Foo> createList = new LinkedList<Foo>();
// add stuff
ArrayList<Foo> returnList = new ArrayList<Foo>(createList);
Collections.sort(returnList);
return returnList;
My question is: Is this method really faster or even slower than just adding the objects directly to an ArrayList? Or, I know the rough number of objects to add. Is an ArrayList with initial capacity faster?
This is related to two questions:
1. What's the difference between ArrayList and LinkedList, which one is faster for insertion?
2. Which one is faster in sorting?
For question 1, the essential difference between ArrayList and LinkedList is the data structure. ArrayList uses an array inside and good at random access(O(1)). On the other hand, LinkedList in good at delete and insert items(O(1). You can find more here
Back to the question, because we don't need to insert by index here.
So ArrayList and LinkedList both O(1) operation. But LinkedList will cause more memory because of the data structure, and ArrayList will cause more time if it needs to scale capacity(set a large enough initial capacity will help speed up the insertion).
For question 2, you can find the answer here
ArrayList is better for sorting.
In conclusion, I think you should stick with ArrayList, no need to import LinkedList here.
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