Skills101

Java Programming · Lesson 11 of 15 · Updated ·

Java Collections — ArrayList, LinkedList, HashSet and Generics

Arrays have a fixed size. The Collections Framework gives you ready, growable data structures — and knowing which to choose is a core interview topic.

The Collections family: Collection splits into List (ArrayList, LinkedList), Set (HashSet, TreeSet) and Queue (ArrayDeque, PriorityQueue); Map (HashMap, TreeMap) is a separate family

1. ArrayList: the everyday list

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> cities = new ArrayList<>();
        cities.add("Jaipur");
        cities.add("Pune");
        cities.add(0, "Delhi");             // insert at index 0
        System.out.println(cities + " size=" + cities.size());
        System.out.println(cities.get(1) + " " + cities.contains("Pune") + " " + cities.indexOf("Pune"));
        cities.remove("Delhi");
        cities.set(0, "Udaipur");
        Collections.sort(cities);
        System.out.println(cities);
    }
}
[Delhi, Jaipur, Pune] size=3
Jaipur true 2
[Pune, Udaipur]
  • <String> is a generic type: this list only accepts Strings, checked at compile time.
  • Collections store objects, so use Integer, not int: List<Integer>.
  • Declare with the interface (List) and create with the class (ArrayList) — easy to switch later.

2. ArrayList vs LinkedList

OperationArrayList (dynamic array)LinkedList (doubly linked)
get(i)O(1)O(n)
add at endO(1) amortisedO(1)
add/remove at start or middleO(n) — shifts elementsO(1) once you're there
Memorycompactextra links per element

Use ArrayList by default. LinkedList is rarely the faster choice in practice.

3. Sets: no duplicates

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = List.of(5, 3, 5, 1, 3, 9);
        Set<Integer> hash = new HashSet<>(nums);         // no order guaranteed
        Set<Integer> linked = new LinkedHashSet<>(nums); // insertion order
        Set<Integer> tree = new TreeSet<>(nums);         // sorted
        System.out.println(hash.size() + " " + linked + " " + tree);
        System.out.println(tree.contains(9) + " " + ((TreeSet<Integer>) tree).first());
    }
}
4 [5, 3, 1, 9] [1, 3, 5, 9]
true 1
HashSetLinkedHashSetTreeSet
Ordernoneinsertionsorted
add / containsO(1)O(1)O(log n)

4. Iterating — and removing safely

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> marks = new ArrayList<>(List.of(35, 80, 20, 92));
        for (int m : marks) System.out.print(m + " ");
        System.out.println();
        marks.removeIf(m -> m < 40);          // safe removal
        System.out.println(marks);
        Iterator<Integer> it = marks.iterator();
        while (it.hasNext()) {
            if (it.next() > 90) it.remove();  // also safe
        }
        System.out.println(marks);
    }
}
35 80 20 92
[80, 92]
[80]

Removing from a list inside a for-each loop throws ConcurrentModificationException. Use removeIf or an Iterator.

5. Queue and Deque in one line each

  • Deque<Integer> stack = new ArrayDeque<>(); → push, pop, peek (use instead of the old Stack class)
  • Queue<Integer> q = new ArrayDeque<>(); → offer, poll, peek
  • PriorityQueue<Integer> pq = new PriorityQueue<>(); → always gives the smallest first (a heap)

Choosing quickly

  • Ordered list, access by index → ArrayList
  • Unique items, fast lookup → HashSet (sorted? TreeSet)
  • Key → value → HashMap (next lesson)
  • Stack or queue → ArrayDeque; smallest/largest first → PriorityQueue

Common mistakes

  • List<int> — generics need objects: List<Integer>.
  • Removing elements inside a for-each loop.
  • list.remove(1) on a List<Integer> removes index 1, not the value 1 — use list.remove(Integer.valueOf(1)).

Quick recap

  • List (ordered, duplicates), Set (unique), Queue/Deque, Map (key-value, separate family).
  • ArrayList is the default list; HashSet the default set.
  • Generics give type safety; use wrapper types.
  • Remove while iterating with removeIf or an Iterator.

Practice what you learned

📝 Quiz: Java Collections (List and Set)5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →