Nearby lessons

83 of 125

Java - List Interface

📌 What You Will Learn
  • What the Collection Framework is and why we need it
  • List, Set, Map and Queue — the four big families
  • Choosing the right collection for the right job
  • Comparable vs Comparator
  • The internal working of HashMap (interview favourite)

List Interface is a core concept of the Java language. This lesson explains List — Ordered, Allows Duplicates and add() vs addAll() with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

List — Ordered, Allows Duplicates

A List keeps values in insertion order and allows duplicates. Each element has an index (position), like an array that can grow.

ArrayList vs LinkedList vs Vector

PointArrayListLinkedListVector
StructureResizable arrayDoubly linked listLike ArrayList but old
Getting by indexVery fast (O(1))Slow (O(n))Fast
Adding/removing in middleSlow (shifting)FastSlow
Thread safe?NoNoYes (synchronized)
When to useMost common choiceFrequent insert/delete in middleLegacy code (avoid for new work)
Example01
JCode Cell
1import java.util.*;
2 
3class ListDemo {
4 public static void main(String[] args) {
5 List<String> list = new ArrayList<>();
6 list.add("Rahul");
7 list.add("Priya");
8 list.add("Rahul"); // duplicate allowed
9 list.add(1, "Anil"); // insert at position 1
10 
11 System.out.println(list);
12 System.out.println("Size: " + list.size());
13 System.out.println("At index 2: " + list.get(2));
14 
15 for (String name : list) { // for-each works on collections too
16 System.out.println(name);
17 }
18 }
19}
Output
[Rahul, Anil, Priya, Rahul] Size: 4 At index 2: Priya Rahul Anil Priya Rahul

add() vs addAll()

  • `add(element)` — adds ONE element.
  • `addAll(collection)` — adds ALL elements of another collection at once. Returns true if the collection changed.
Example02
JCode Cell
1import java.util.*;
2 
3class AddAllDemo {
4 public static void main(String[] args) {
5 HashSet<String> set1 = new HashSet<>(List.of("A", "B", "C"));
6 HashSet<String> set2 = new HashSet<>();
7 
8 System.out.println(set2.addAll(set1)); // true - changed
9 System.out.println(set2); // [A, B, C]
10 System.out.println(set2.addAll(set1)); // false - nothing new
11 }
12}
Output
true [A, B, C] false
📝 Key Takeaways
  • Collection is an interface; Collections is a utility class with static helpers.
  • List = ordered, allows duplicates. Set = no duplicates. Map = key-value pairs. Queue = FIFO.
  • ArrayList is the everyday list; HashMap is the everyday map.
  • HashMap works on hashCode + buckets; collisions chain, then become trees (Java 8+).
  • Comparable (compareTo) is the natural order; Comparator (compare) gives custom order.
  • Always override equals() and hashCode() together for your own objects.
  • Collections.sort() and Collections.reverse() are the handy helpers.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1