1.List Interface :
The List interface is part of java.util and extends the Collection interface. It represents an ordered sequence of elements — you can access any element by its position (index).
- It is Ordered
- It Allows duplicates
- Index-based access
import java.util.List;
import java.util.ArrayList;
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
System.out.println(fruits.get(0)); // Output: Apple
The 2 main implementations :
Arraylist:
- Elements sit side-by-side in memory. Jump to any index instantly — like numbered boxes in a row.
- It stores elements in a contiguous block of memory, so get(5) jumps straight to position 5 — like page numbers in a book. This is called O(1) or "constant time."
-When you use ArrayList :
- You read or access elements often
- You mostly add to the end of the list
- Memory efficiency matters
- You need to iterate in order
Linkedlist:
Each node holds the value + a pointer to next. Scattered in memory must walk the chain to find an element.
Each element is a node that holds a pointer to the next. Inserting means just rewiring two pointers — no shifting needed. ArrayList, on the other hand, has to push every element after the insertion point one slot over.
-When you use Linkedlist :
- You insert/delete in the middle often
- You need a Queue or Deque structure
- List size changes frequently
- You process from both ends
Common List methods :
1.Add() — insert elements :
fruits.add("Grapes"); // Adds to end
fruits.add(1, "Cherry"); // Adds at index 1
2.get() & size() — access & count :
String first = fruits.get(0); // "Apple"
int total = fruits.size(); // Total items
3.remove() — delete elements :
fruits.remove("Banana"); // Remove by value
fruits.remove(0); // Remove by index
Top comments (0)