1. Overview
In this super-quick tutorial, weβll show how to remove the first element from a List.
Weβll perform this operation for two common implementations of the List interface β ArrayList and LinkedList.
2. Creating a List
Firstly, letβs populate our Lists:
@Before
public void init() {
list.add("cat");
list.add("dog");
list.add("pig");
list.add("cow");
list.add("goat");
linkedList.add("cat");
linkedList.add("dog");
linkedList.add("pig");
linkedList.add("cow");
linkedList.add("goat");
}
3. ArrayList
Secondly, letβs remove the first element from the ArrayList, and make sure that our list doesnβt contain it any longer:
@Test
public void givenList_whenRemoveFirst_thenRemoved() {
list.remove(0);
assertThat(list, hasSize(4));
assertThat(list, not(contains("cat")));
}
As shown above, weβre using remove(index) method to remove the first element β this will also work for any implementation of the List interface.
4. LinkedList
LinkedList also implements remove(index) method (in its own way) but it has also the removeFirst() method.
Letβs make sure that it works as expected:
@Test
public void givenLinkedList_whenRemoveFirst_thenRemoved() {
linkedList.removeFirst();
assertThat(linkedList, hasSize(4));
assertThat(linkedList, not(contains("cat")));
}
5. Time Complexity
Although the methods look similar, their efficiency differs. ArrayListβs remove() method requires O(n) time, whereas LinkedListβs removeFirst() method requires O(1) time.
This is because ArrayList uses an array under the hood, and the remove() operation requires copying the rest of the array to the beginning. The larger the array is, the more elements need to be shifted.
Unlike that, LinkedList uses pointers meaning that each element points to the next and the previous one.
Hence, removing the first element means just changing the pointer to the first element. This operation always requires the same time not depending on the size of a list.
6. Conclusion
In this article, weβve covered how to remove the first element from a List, and have compared the efficiency of this operation for ArrayList and LinkedList implementations.
