Lesson 37
ArrayList and LinkedList
ArrayList for fast access. LinkedList for fast insert and delete.
Java Track
Save progress as you learn.
61 lessons
Lesson content
Both implement List. ArrayList uses array. LinkedList uses nodes.
Key Terms
- ArrayList: Dynamic array. Fast index access.
- LinkedList: Doubly linked nodes. Fast insert/delete.
- List Interface: Ordered, allows duplicates.
- Dynamic Size: Grows and shrinks automatically.
Example: ArrayList
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
System.out.println(fruits);
System.out.println("First Fruit: " + fruits.get(0));
}
}[Apple, Banana, Mango]
First Fruit: AppleExample: LinkedList
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> fruits = new LinkedList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
System.out.println(fruits);
System.out.println("First Fruit: " + fruits.get(0));
}
}[Apple, Banana, Mango]
First Fruit: AppleCommon Operations
list.add("Java"); // add
list.get(0); // access
list.set(0, "Python"); // update
list.remove(0); // remove
list.size(); // sizeIterating
for (String item : list) {
System.out.println(item);
}When to Use Each
- ArrayList: Frequent reads, index access.
- LinkedList: Frequent inserts and deletes.
- LinkedList: Queue or deque operations.
FAQ
1. Main difference?
ArrayList — fast access. LinkedList — fast insert/delete.
2. Which is faster?
ArrayList for reads. LinkedList for modifications.
3. When LinkedList over ArrayList?
Frequent insert/delete at middle or beginning.
ArrayList — dynamic array, fast index access.
LinkedList — nodes with links, fast modifications.
Both allow duplicates and maintain order.
ArrayList uses less memory.
LinkedList faster at insert and delete.
Use ArrayList by default.
Program to List interface, not implementation.
Where Java is used
Java in real-world development
ArrayList
Dynamic array. Fast get(). Slower middle insert/delete.
LinkedList
Doubly linked nodes. Fast insert/delete. Slower random access.
Memory
ArrayList uses less. LinkedList stores prev/next references.
Use ArrayList When
More reads than writes. Index access needed.
Use LinkedList When
Frequent insert/delete. Queue or deque needed.
Best Practice
List<String> names = new ArrayList<>() — program to interface.