Chapter 5 · Simulation

Collections Internals

← Chapter 5
List<String> list = new ArrayList<>(4);

Collections Internals

Goal: see what the methods of ArrayList and HashMap do inside, and how many units of work they cost.

ArrayList

  • The elements are kept in an internal array. size() is the number of filled cells; the capacity is the length of the array.
  • When the array is full, the new capacity becomes old + old / 2 (about 1.5 times) and all elements are copied into the new array. new ArrayList<>() allocates the array with 10 cells on the first add call.
  • add(i, e) and remove(i) shift the elements after i by one cell: O(n). get(i) and appending at the end are O(1); the occasional copy makes appending amortized O(1).

HashMap

  • The key's hashCode() is mixed with h ^ (h >>> 16); & (n − 1) takes the last bits and gives the bucket number (n: number of buckets, a power of 2).
  • Entries that fall into the same bucket form a chain (linked list). A lookup compares the hashes first; equals is called only if the hashes are equal. "Aa" and "BB" have the same hashCode() (2112).
  • When the number of entries exceeds the threshold (number of buckets × 0.75), the number of buckets doubles; each entry either stays in the same bucket or moves to bucket i + old n.
  • When a chain grows beyond 8 entries, Java turns it into a tree (growing the table first if it is small); this simulator shows at most 8 entries per bucket and at most 24 in total.

How to use it

  1. Choose a structure on the left and press an operation button. The operation plays step by step; if Play automatically is off, advance with Step ▶ (keyboard →); To end ⏭ finishes the operation.
  2. The counters at the bottom show unit operations: shifts, copies, comparisons, re-placements.
  3. With Test yourself on, you predict before the operation how many elements will shift, the new capacity or the bucket number.
  4. The Compare tab puts the approximate step counts of typical operations side by side for a structure with n elements.

The capacity arrays and bucket placement were checked against the internal fields of real Java 8 ArrayList and HashMap objects with the same keys.

Related slides: Chapter 5 · Collections (How Does an ArrayList Grow?, Inserting and Removing in the Middle, HashSet and Hashing, The HashMap Class).