Core Java · 6. Collections, lesson 3 of 27

Every List, Set and Queue: ArrayList to BlockingQueue

Intermediate6 min read@since 21Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

## Lists — keep a sequence A List preserves position and allows duplicates.

  • ArrayList: default for product lists, API results, student marks, cart items. get(index) is fast; adding at the end is usually cheap. Inserting at index 0 shifts the remaining elements.
  • LinkedList: nodes link to previous/next nodes. It is not automatically faster for insert/delete: finding index 5,000 still requires traversal. Consider it only for iterator-local edits; for queues/stacks, prefer ArrayDeque.
  • List.of(…): concise constants (HTTP allowed methods, fixed status labels); unmodifiable and rejects nulls. Wrap in `new ArrayList<>(...)` if you need to edit.

Scenario: A checkout cart is a List because line order matters and the same product may appear as separate lines with different variants. A Set would silently remove duplicates; a Map would require a product key and change the model.

## Sets — enforce uniqueness

  • HashSet: membership checks and duplicate removal (unique enrolled course IDs); no order guarantee.
  • LinkedHashSet: unique values in first-seen order (deduplicated search suggestions).
  • TreeSet: unique values sorted (roll numbers, score thresholds); use `first`, `ceiling`, `floor`, `headSet` for ranges.

Scenario: Validate a batch of registration emails: add normalized emails to a Set; if add() returns false, the email appeared earlier. A database unique constraint is still needed for correctness across concurrent requests.

## Queues and deques — decide who is next

  • Queue / ArrayDeque: FIFO; offer adds, poll removes (returns null if empty), peek observes. Example: in-memory tasks waiting to be processed.
  • Deque / ArrayDeque: both ends; push/pop at the front for LIFO undo, or addLast/removeFirst for FIFO.
  • PriorityQueue: heap; `peek/poll` returns the least element by default, or highest priority with a reversed Comparator. Example: urgent support tickets. Do not expect its iterator to be sorted.
  • BlockingQueue: producer/consumer coordination between threads; take() waits when empty. Example: worker threads consume email jobs. Use bounded queues to apply back-pressure.

Remove items safely with removeIf or an Iterator's `remove`. Java 21's sequenced collections add getFirst, getLast, and reversed to lists, deques and ordered collections.

ArrayList

A resizable array: the default List. Fast index access (O(1)), fast appends (O(1) on average), slower inserts and removals in the middle (O(n)). Not thread-safe. Use it unless you have a specific reason not to.

Java
List<String> courses = new ArrayList<>(List.of("Java", "Spring"));
courses.add("Docker");
courses.add(1, "SQL");                 // [Java, SQL, Spring, Docker]
courses.set(0, "Java 25");
courses.remove("Spring");
System.out.println(courses.get(1));    // SQL
Array lab

LinkedList

A doubly linked list that implements both List and Deque. Adding or removing at either end is O(1), but reaching an index is O(n), and each element carries extra memory. In practice it's rarely the best choice; see "ArrayList vs LinkedList".

Java
LinkedList<String> history = new LinkedList<>();
history.addFirst("/learn/streams");
history.addFirst("/learn/lambdas");
history.removeLast();                  // O(1) at either end
System.out.println(history.getFirst());   // /learn/lambdas
LinkedList lab

Vector (legacy)

The Java 1.0 ancestor of ArrayList. Every method is synchronized, so it's slower even in single-threaded code, and it grows by doubling. Its synchronization doesn't make multi-step operations safe either. Use ArrayList, and for shared lists use CopyOnWriteArrayList (read-mostly) or Collections.synchronizedList with care.

Array lab

Stack (legacy)

A last-in, first-out stack with push, pop and peek. It extends Vector, so it's synchronized and also exposes list methods like add(index, e), letting code break the stack's rules. The Javadoc itself recommends Deque instead: ArrayDeque has the same push/pop/peek and is faster.

Java
Deque<String> undo = new ArrayDeque<>();   // use this instead of Stack
undo.push("typed 'Hello'");
undo.push("made it bold");
System.out.println(undo.pop());            // made it bold   (last in, first out)
System.out.println(undo.peek());           // typed 'Hello'
ArrayDeque lab

HashSet

Unique elements with no order, backed by a HashMap. add, contains and remove are O(1) on average, which makes it the go-to for "have I seen this before?". Elements need correct equals() and hashCode().

Java
Set<String> seenEmails = new HashSet<>();
for (String email : signups) {
    if (!seenEmails.add(email.toLowerCase())) {     // add() returns false for duplicates
        System.out.println("Duplicate sign-up: " + email);
    }
}
HashMap lab

LinkedHashSet

A HashSet that also remembers insertion order. Nearly as fast, a little more memory. The easiest way to remove duplicates while keeping the original order.

Java
List<String> tags = List.of("java", "spring", "java", "sql", "spring");
Set<String> unique = new LinkedHashSet<>(tags);
System.out.println(unique);            // [java, spring, sql]   first-seen order kept
LinkedHashMap lab

TreeSet

Unique elements kept sorted, backed by a red-black tree (TreeMap). Operations are O(log n). Adds navigation methods: first, last, floor, ceiling, headSet, tailSet, descendingSet. Uniqueness comes from compareTo() or your Comparator.

Java
TreeSet<Integer> scores = new TreeSet<>(List.of(72, 95, 88, 60));
scores.first();            // 60
scores.ceiling(80);        // 88    smallest score >= 80
scores.headSet(88);        // [60, 72]
scores.descendingSet();    // [95, 88, 72, 60]
TreeMap lab

PriorityQueue

A queue that always hands out the smallest element first (natural order or a Comparator), implemented as a binary heap. offer and poll are O(log n), peek is O(1). Great for scheduling by priority and "top k" problems. Two catches: iterating it isn't sorted (only poll order is), and it isn't thread-safe (PriorityBlockingQueue is).

Java
record Task(String name, int priority) {}
PriorityQueue<Task> tasks = new PriorityQueue<>(Comparator.comparingInt(Task::priority));
tasks.offer(new Task("send newsletter", 3));
tasks.offer(new Task("fix payment bug", 1));
tasks.offer(new Task("update docs", 2));

while (!tasks.isEmpty()) System.out.println(tasks.poll().name());
// fix payment bug, update docs, send newsletter
PriorityQueue lab

ArrayDeque

A resizable circular array usable as a stack (push, pop) or a queue (offer, poll), with O(1) operations at both ends. Faster than Stack and usually faster than LinkedList. It doesn't allow null.

Java
Deque<String> queue = new ArrayDeque<>();
queue.offer("Asha");                   // join at the back
queue.offer("Ravi");
System.out.println(queue.poll());      // Asha   first in, first out

Deque<Character> brackets = new ArrayDeque<>();   // as a stack: check balanced brackets
for (char c : "(a[b]c)".toCharArray()) {
    if (c == '(' || c == '[') brackets.push(c);
    else if (c == ')' || c == ']') brackets.pop();
}
ArrayDeque lab

BlockingQueue

A thread-safe queue whose put() waits when it's full and take() waits when it's empty: the standard tool for handing work between threads. Implementations: ArrayBlockingQueue (bounded array), LinkedBlockingQueue (optionally bounded), PriorityBlockingQueue, DelayQueue (items become available after a delay) and SynchronousQueue (a direct hand-off with no storage). The concurrency lesson shows a full producer-consumer example.

Java
BlockingQueue<String> jobs = new LinkedBlockingQueue<>(1_000);
jobs.put("resize-image-42");                          // waits if full
String job = jobs.poll(2, TimeUnit.SECONDS);          // waits up to 2 s, then returns null
BlockingQueue lab

Example

Java
// Shopping cart: order and duplicate lines are allowed
record CartLine(String sku, int quantity) {}
List<CartLine> cart = new ArrayList<>();
cart.add(new CartLine("BOOK-JAVA", 1));
cart.add(new CartLine("BOOK-JAVA", 2));               // separate line is valid
cart.removeIf(line -> line.quantity() <= 0);            // remove invalid lines

// Registration import: detect duplicate emails while preserving first-seen order
Set<String> importedEmails = new LinkedHashSet<>();
boolean firstOccurrence = importedEmails.add("asha@example.com"); // true
boolean duplicate = importedEmails.add("asha@example.com");     // false

// Sorted marks: find next score threshold
NavigableSet<Integer> scores = new TreeSet<>(List.of(55, 72, 91, 38));
System.out.println(scores.ceiling(60));                   // 72
System.out.println(scores.headSet(60));                   // [38, 55]

// Browser back stack: newest page is on top
Deque<String> history = new ArrayDeque<>();
history.push("/home");
history.push("/courses");
history.push("/courses/java");
history.pop();                                            // /courses/java removed
System.out.println(history.peek());                       // /courses

// Support queue: priority 10 is more urgent than priority 1
record Job(String name, int priority) {}
PriorityQueue<Job> jobs = new PriorityQueue<>(Comparator.comparingInt(Job::priority).reversed());
jobs.offer(new Job("email", 1));
jobs.offer(new Job("payment outage", 10));
System.out.println(jobs.poll().name());                  // payment outage

// FIFO worker queue (single-threaded illustration)
Queue<String> work = new ArrayDeque<>();
work.offer("send-welcome");
work.offer("send-receipt");
System.out.println(work.poll());                           // send-welcome

System.out.println(cart.getFirst());                      // Java 21+

Common mistake

Using Stack or LinkedList as a stack. Stack is a synchronized legacy class; ArrayDeque is faster and recommended.

Under the hood

Iterating a PriorityQueue doesn't give sorted order; only repeated poll() does, because it's a binary heap (O(log n) insert and poll, O(1) peek). ArrayDeque rejects null because null means "empty" from poll(). For thread-safe hand-offs between threads, use a BlockingQueue such as LinkedBlockingQueue.

Check yourself

Which class is recommended for a stack?

How this connects

Part of Java from zero, Upgrade from Java 8 to Java 25, Java 8 and collections, practically.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.