ArrayList vs LinkedList in Java with Examples
#ArrayList vs LinkedList in Java with Examples
Both ArrayList and LinkedList are popular implementations of the List interface in Java. They provide different ways of storing and managing data, making them suitable for different scenarios. Let’s explore their differences with examples.
Definition: Uses a dynamic array to store elements.
Best For: Fast random access and iteration.
Performance:
Access: O(1)
Insertion (end): O(1) amortized
Insertion/Deletion (middle): O(n)
Example:
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
System.out.println("ArrayList: " + fruits);
}
}
Definition: Uses a doubly linked list to store elements.
Best For: Frequent insertions and deletions.
Performance:
Access: O(n)
Insertion/Deletion (start or middle): O(1)
Iteration: O(n)
Example:
import java.util.*;
public class LinkedListExample {
public static void main(String[] args) {
List<String> animals = new LinkedList<>();
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
System.out.println("LinkedList: " + animals);
}
}
Feature | ArrayList | LinkedList |
---|---|---|
Data Structure | Dynamic Array | Doubly Linked List |
Access Speed | Fast (O(1)) | Slower (O(n)) |
Insertion/Deletion | Slow in middle (O(n)) | Fast at beginning/middle (O(1)) |
Memory Usage | Less memory overhead | More memory (due to node pointers) |
Use ArrayList when you need fast access and iteration.
Use LinkedList when you need frequent insertions/deletions.
Avoid LinkedList when memory is a concern.
Both ArrayList and LinkedList implement the List interface, but their internal workings make them suitable for different use cases. By understanding their differences, you can make better decisions about which collection to use in your Java applications.