I am implementing a public method that needs a data structure that needs to be able to handle insertion at two ends. Since ArrayList.add(0,key)
will take O(N) time, I decide to use a LinkedList
instead - the add
and addFirst
methods should both take O(1) time.
However, in order to work with existing API, my method needs to return an ArrayList
.
So I have two approaches:
(1) use LinkedList
,
do all the addition of N elements where N/2 will be added to the front and N/2 will be added to the end.
Then convert this LinkedList
to ArrayList
by calling the ArrayList
constructor:
return new ArrayList<key>(myLinkedList);
(2) use ArrayList
and call ArrayList.add(key)
to add N/2 elements to the back and call ArrayList.add(0,key)
to add N/2 elements to the front. Return this ArrayList
.
Can anyone comment on which option is more optimized in terms of time complexity? I am not sure how Java implements the constructor of ArrayList
- which is the key factor that decides which option is better.
thanks.