Skip to main content
Intermediate Step-by-Step Tutorial 11 min read Java 8–21 LTS

Java Collections Framework: ArrayList vs HashMap & Internals

Choose the exact List, Set, Queue, and Map implementation by understanding amortized time complexity, hash buckets, and Java 8+ treeification.

Written by MockAttempt Engineering Editorial Desk (Curriculum & Code Verification Review Panel) Reviewed by Ravi Shankar Mishra
Last updated: Verification Policy

Learning Objectives

  • Compare `ArrayList` and `LinkedList` by CPU cache locality, indexed reads, and mid-list insertions.
  • Trace how `HashMap` computes bucket indices, resolves collisions, and treeifies at threshold 8 (Java 8+).
  • Maintain the `equals()` and `hashCode()` contract cleanly so HashMap lookups never lose keys.

Prerequisites

  • Java Classes, Objects, Interfaces, and Generics basics

Choosing Collections by Access Pattern

Choosing between ArrayList, HashSet, ArrayDeque, and HashMap determines whether an API endpoint scales linearly or hits quadratic slowdowns under load.

CollectionBacking StructureAvg Read / LookupOrdering
ArrayListResizable Object[] arrayO(1) by indexInsertion order
ArrayDequeCircular resizable arrayO(1) head/tail push/popFIFO / LIFO (faster than Stack/LinkedList)
HashMapBucket array + linked/tree binsO(1) avg (O(log n) worst Java 8+)Unordered (LinkedHashMap preserves order)
TreeMapRed-Black balanced BSTO(log n)Sorted by natural/Comparator order

How HashMap Works Since Java 8

When calling map.put(key, val), HashMap mixes high/low hash bits via (h = key.hashCode()) ^ (h >>> 16) to reduce lower-bit clustering, indexes into a power-of-two array (`(n - 1) & hash`), and checks key equality with equals(). Since Java 8, once a single bucket exceeds TREEIFY_THRESHOLD = 8 (with table capacity >= 64), the linked nodes convert to a balanced Red-Black tree so pathological hash collisions degrade to O(log n) instead of O(n).

Up next: transform collections declaratively in Java Stream API & Lambdas or drill Collections MCQs in MockAttempt Mock Tests.

Practical Programming Examples

Grouping, Frequency Counting & Map.computeIfAbsent in Java

Group engineering topics by category cleanly using computeIfAbsent and immutable defensive views.

JDK 21 LTS (javac / java)
import java.util.*;

public class CollectionsLab {
    public static void main(String[] args) {
        Map<String, List<String>> curriculum = new LinkedHashMap<>();
        curriculum.computeIfAbsent("Backend", k -> new ArrayList<>()).add("Spring Boot 3");
        curriculum.computeIfAbsent("Backend", k -> new ArrayList<>()).add("PostgreSQL MVCC");
        curriculum.computeIfAbsent("Cloud", k -> new ArrayList<>()).add("AWS VPC & IAM");

        curriculum.forEach((track, topics) ->
            System.out.println(track + " -> " + List.copyOf(topics))
        );
    }
}
Expected Output
Backend -> [Spring Boot 3, PostgreSQL MVCC]
Cloud -> [AWS VPC & IAM]
Step-by-Step Execution
  1. `LinkedHashMap` preserves insertion order deterministically while preserving O(1) bucket lookups.
  2. `computeIfAbsent` inserts a backing list once per missing key, eliminating noisy `containsKey` null checks.
  3. `List.copyOf` returns an unmodifiable view safe for logging or read serialization.

Common Mistakes to Avoid

  • Overriding `equals()` on a domain key class without overriding `hashCode()`, breaking HashMap/HashSet lookups completely.
  • Modifying a key’s hashable field after placing it inside a `HashMap` or `HashSet`.
  • Removing items inside a `for-each` loop instead of `Iterator.remove()` or `collection.removeIf(...)`, triggering `ConcurrentModificationException`.

Production Best Practices

  • Prefer `ArrayDeque` over legacy `Stack` or `LinkedList` when implementing queues or stacks.
  • Use `List.of()`, `Set.of()`, and `Map.of()` (Java 9+) for small fixed read-only lookups.

Technical Interview Relevance

Nearly every Java fresher and experienced backend interview asks about HashMap collision resolution, fail-fast iterators (`modCount`), and `ConcurrentHashMap`.

Practice & Self-Check Questions

Why does `LinkedList` perform poorly compared to `ArrayList` even for sequential scans?

LinkedList nodes scatter across heap memory (`Node` wrappers + pointers), destroying CPU cache spatial locality and adding 24+ bytes of memory overhead per element.

Optional Next Step

Have Questions About Learning Core Java Structured Cohorts?

Request the JBCP syllabus & weekend batch schedule from an Academic Counselor.

View JBCP Details →
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.