Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java collections cheatsheet: operation contracts and failure cases

Last updated: 28 Sept 20263 min read
tutorial
IntermediateBy AITrove Editorial

A collection choice is a choice of ordering, equality, access cost, ownership, and failure behavior rather than a preference for a class name.

Java 8+. Use a JDK that supports this release.

Lists and deques

ArrayList gives constant-time indexed access and amortised constant-time append. Inserting near the front shifts references. Removing by value still requires finding that value.

LinkedList gives constant-time endpoint edits, but finding an indexed position requires traversal. An insertion through an already positioned iterator has a different cost from an indexed insertion.

ArrayDeque is a common single-threaded stack or queue choice. It rejects null. poll returns null on an empty deque; remove throws. Choose the absence contract deliberately.

Maps, sets, and ordering

HashMap has no encounter-order promise. LinkedHashMap defines encounter behavior. TreeMap orders by keys and provides range queries.

HashSet uses equality and hashing for membership. Mutating an equality-relevant field of a stored key or element breaks the lookup assumption. Tree-based keys use comparison equivalence to decide uniqueness.

PriorityQueue removes according to priority, but iterating it does not sort all elements. Repeated poll changes the queue; copy it if the original must remain intact.

Iteration and snapshots

Use Iterator.remove only when that iterator’s contract supports removal. A fail-fast exception is a bug signal, not a guaranteed concurrent-change detector or a synchronization mechanism.

An unmodifiable view can still reflect backing-store edits. A copied collection separates the structure but may share mutable elements. State which layer is copied.

Thread-safe individual operations do not automatically make a check-then-act sequence safe. A compound invariant needs a compound operation or a synchronization owner.

Cost and design choices

Expected hashing bounds assume usable hash distribution and bounded key costs. Ordered structures include comparison work. Always count the search needed to reach an edit position.

This reference lists major contracts covered by the library. Specialized concurrent, blocking, weak-reference, and immutable-collection APIs remain separate study areas.

Common Mistakes

  • Do not infer ordering from a small sample printout.
  • Do not omit the cost of reaching an insertion point.
  • Do not claim an unmodifiable view is a detached deep copy.
java
collections-cheatsheet
Storage details