Classes implementing List - Pros and Conssuggest change
List interface is implemented by different classes. Each of them has its own way for implementing it with different strategies and providing different pros and cons.
Classes implementing List
These are all of the
public classes in Java SE 8 that implement the
- Abstract Classes:
- AbstractList - AbstractSequentialList
- Concrete Classes:
- ArrayList - AttributeList - CopyOnWriteArrayList - LinkedList - RoleList - RoleUnresolvedList - Stack - Vector
Pros and Cons of each implementation in term of time complexity
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
ArrayList is a resizable-array implementation of the List interface. Storing the list into an array, ArrayList provides methods (in addition to the methods implementing the List interface) for manipulating the size of the array.
Initialize ArrayList of Integer with size 100
List<Integer> myList = new ArrayList<Integer>(100); // Constructs an empty list with the specified initial capacity.
The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. So getting and setting each element of the List has the same time cost:
int e1 = myList.get(0); // \ int e2 = myList.get(10); // | => All the same constant cost => O(1) myList.set(2,10); // /
Being implemented with an array (static structure) adding elements over the size of the array has a big cost due to the fact that a new allocation need to be done for all the array. However, from documentation:
The add operation runs in amortized constant time, that is, adding n elements requires O(n) time
Removing an element requires O(n) time.
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable
Iitialize LinkedList of Integer
List<Integer> myList = new LinkedList<Integer>(); // Constructs an empty list.
Adding or removing an element to the front of the list or to the end has constant time.
myList.add(10); // \ myList.add(0,2); // | => constant time => O(1) myList.remove(); // /
- CONS: From documentation:
Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
Operations such as:
myList.get(10); // \ myList.add(11,25); // | => worst case done in O(n/2) myList.set(15,35); // /