The inefficiency of using List
is endemic to the problem. Every time you add something, every subsequent element will have to be re-indexed - as the javadoc states:
Shifts the element currently at that position (if any) and any
subsequent elements to the right (adds one to their indices).
From your question/comments, it would appear that you have a bunch of Object
s, and you're sorting them as you go. I'd suggest a more efficient solution to this problem would be to write a Comparator
(or make your object implement Comparable
), and then use Collections.sort(list, comparator)
(or Collections.sort(list)
).
You might suggest that your Object
s are being sorted on the basis of other variables. In which case, you could create an extension of the Object
, with those other variables as fields and extending Comparable
, and with a method like getOriginal()
. You add these wrapped objects to your list, sort, and then iterate through the list, adding the original objects (from getOriginal()
) to a new list.
For info on the sorting algorithm of collections - see this SO question