In the preceding chapter, you became acquainted with the ArrayList class. The LinkedList class shares considerable similarity with ArrayList.
// Import the LinkedList class
|
In the preceding chapter, you became acquainted with the ArrayList class. The LinkedList class shares considerable similarity with ArrayList.
The LinkedList class possesses identical methods to the ArrayList class since they both implement the List interface. This implies that you can add, modify, remove, and clear items from the list in the same manner.
Although the ArrayList class and the LinkedList class can be utilized in a similar manner, they are constructed in fundamentally different ways.
Within the ArrayList class, there exists a conventional array. Upon adding an element, it is inserted into this array. If the array’s capacity is insufficient, a new, larger array is generated to substitute the old one, which is then discarded.
In a LinkedList, items are stored in “containers.” The list maintains a reference to the first container, and each container holds a reference to the next container in the list. When adding an element to the list, it is placed into a new container, which is then linked to another container in the list.
When To UseUtilize an ArrayList for storage and access of data, and LinkedList for data manipulation. |
In many situations, the ArrayList is preferable due to the frequent need for random access to items in the list. However, the LinkedList offers various methods optimized for certain operations’ efficiency.
Method |
Description |
addFirst() |
Insert an item at the start of the list. |
addLast() |
Append an item to the end of the list. |
removeFirst() |
Remove an item from the beginning of the list. |
removeLast() |
Remove an item from the end of the list. |
getFirst() |
Retrieve an item at the beginning of the list. |
getLast() |
Retrieve an item at the end of the list. |