ArrayLists and LinkedLists in Java
ArrayLists and LinkedLists in Java
Lists are ordered collections that allow duplicates. Java provides several implementations, including
Both are part of the java.util package and implement the List interface.
ArrayList
Performance Characteristics:
- Insertion at end: O(1), except when resizing is needed (then it's O(n)).
Usage Scenarios:
- Less efficient for frequent insertions or deletions, especially at the beginning or middle.
Example:
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.get(1); // Returns "Banana"
LinkedList
Underlying Structure: Consists of nodes where each node holds a reference to the previous and
next node.
Performance Characteristics:
Usage Scenarios:
- Preferred when frequent insertions or deletions at the beginning or middle are required.
Example:
linkedList.add("Apple");
linkedList.add("Banana");
- Insertion and Deletion: LinkedList is generally faster for insertions and deletions, especially at
- Memory Overhead: LinkedList requires more memory per element (due to storing node
references).
Example Comparisons
Adding Elements:
Removing Elements:
start = System.currentTimeMillis();
Conclusion
Both ArrayList and LinkedList are powerful data structures but have different strengths.
Understanding the performance implications helps in choosing the right list for specific use cases.