For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt, and this page is available as Markdown at https://nhanbe.id.vn/java/collections.md.
The Java Collections Framework is the backbone of everyday Java programming. Choosing
the right collection type impacts performance, correctness, and readability. This page
covers the core types, immutable collections, concurrent alternatives, and a decision
guide.
Backed by a resizable array. Fast random access, slow insertion in the middle.
List<String> names = new ArrayList<>();names.add("Alice");names.add("Bob");names.add(1, "Charlie"); // insert at index 1String first = names.get(0); // O(1)names.remove("Bob");
Doubly-linked list. Fast insertion/removal at both ends, slow random access.
LinkedList<String> deque = new LinkedList<>();deque.addFirst("first");deque.addLast("last");String head = deque.getFirst(); // O(1)deque.removeFirst(); // O(1)
Use ArrayList by default. Use LinkedList only when you need a Deque (double-ended
queue) with frequent head/tail operations and never index into the middle.
Backed by a HashMap. Fast lookups, no ordering guarantee.
Set<String> tags = new HashSet<>();tags.add("java");tags.add("streams");tags.add("java"); // ignored (duplicate)boolean has = tags.contains("java"); // O(1) average
Maintains sorted order (natural or custom Comparator):
Set<String> sorted = new TreeSet<>();sorted.add("banana");sorted.add("apple");sorted.add("cherry");// Iteration order: apple, banana, cherry// With custom comparator (case-insensitive)Set<String> ci = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
Thread-safe list optimised for read-heavy workloads. Writes create a new copy
of the underlying array:
CopyOnWriteArrayList<String> listeners = new CopyOnWriteArrayList<>();listeners.add("listener1"); // creates a new array copy// Safe to iterate while another thread adds/removesfor (String listener : listeners) { notify(listener);}
BlockingQueue<String> queue = new LinkedBlockingQueue<>(100);// Producerqueue.put("task1"); // blocks if queue is full// ConsumerString task = queue.take(); // blocks if queue is empty// With timeoutString taskOrNull = queue.poll(5, TimeUnit.SECONDS); // returns null on timeout