I am implementing a public method that needs a data structure that should be able to handle insertion from two ends. Since ArrayList.add(0,key) will take O (N) time, I decided to use LinkedList instead - the add and addFirst should take as O (1) time.
However, to work with the existing API, my method must return an ArrayList . Therefore, I have two approaches:
(1) use LinkedList , do all adding N elements where N / 2 will be added to the beginning 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 in the opposite direction and call ArrayList.add(0,key) to add N / 2 elements. front. Return this ArrayList value.
Can someone comment on which option is more optimized in terms of time complexity? I'm not sure how Java implements the ArrayList constructor - which is the key factor that decides which option is better.
thanks.
source share