Lesson · Collections Framework
The rest of java.util: bits, ids, joining, randomness
13 min readOther Data Structures in java.util
Beyond lists and maps, java.util hides dense BitSets, UUIDs, StringJoiner and the Random family. Each has one job it does better than any collection, and each shows up in interviews and real code.
Not everything is a List
Track which of a million ids have been seen. Three tools fit, and only one is built for the shape of the question:
Set<Integer>holds the seen ids as boxed objects: fast membership, but roughly forty bytes per id.boolean[]is dense and fast, but needs the id as a direct index and a byte per flag.BitSetpacks one bit per id, answersget, counts withcardinality, and set algebra (and,or,xor) comes free.
The rule of thumb: sparse values, use a Set; dense small-domain flags, use a BitSet or a boolean array. This lesson tours the rest of the toolbox with the same eye for shape.
Odd tools shelf · each answers a shape
pick a toolOne bit per number: bits 0 to 7
2, 5 and flipped 4 are set: three bits on, five off, and the whole row costs one byte. A Set<Integer> would hold three boxed integers instead.
BitSet, as code
seen.set(2); seen.set(5); seen.flip(4);
givescardinality() = 3 · nextSetBit(3) = 4
Dense flags over a bounded range of ids, with free set algebra.
Sparse values point to a Set; dense bounded flags point to a BitSet. The other three each replace a manual loop or a wrong tool choice.
BitSet: dense flags, one bit each
A BitSet is a growable row of bits with efficient bulk operations:
BitSet seen = new BitSet(); seen.set(2); seen.set(5); seen.set(2); // setting twice is one bit System.out.println(seen.cardinality()); // 2 how many are set System.out.println(seen.get(5)); // true seen.flip(4); System.out.println(seen.nextSetBit(3)); // 4 first set bit at or after 3
- Bulk algebra:
and,or,xorandandNotcombine whole sets in word-sized steps. - Iterating set bits:
nextSetBitwalks only the ones, not the whole range. - Sparse danger: a BitSet sized by the largest id allocates for every id below it. A Set holds only what is present.
StringJoiner and String.join
Joining strings used to be a manual loop with a flag for the separator. The modern tools fold it into one object or one call:
StringJoiner joiner = new StringJoiner(", ", "[", "]"); joiner.add("ada").add("grace"); System.out.println(joiner); // [ada, grace] System.out.println(String.join(" | ", "a", "b", "c")); // a | b | c
StringJoinercarries a separator, an optional prefix and suffix, and amergemethod for combining partial joins.String.joinis the one-shot version when you already have all the pieces.- Both beat hand-rolled loops on readability and on the off-by-one separator bugs.
UUID: 128 random or derived bits
An identifier that needs no coordination with a database:
UUID parsed = UUID.fromString("123e4567-e89b-12d3-a456-426614174000"); System.out.println(parsed.version()); // 1: time-based layout System.out.println(parsed.variant()); // 2: IETF UUID fresh = UUID.randomUUID(); // version 4, 122 random bits
- randomUUID is cryptographically seeded and collision odds are negligible: safe as a primary key or correlation id without a central counter.
- version and variant describe the bit layout;
fromStringaccepts the canonical hyphenated form. - UUID is not an ordering. Version 4 values scatter; for time-ordered ids look at the sorted UUID variants or a database sequence.
The Random family
Four tools share the word random, with different promises:
| Tool | Promise | Use for |
|---|---|---|
new Random(seed) | reproducible sequence for a given seed | tests, simulations, replays |
ThreadLocalRandom.current() | fast, per-thread, not reproducible | parallel code that avoids contention |
SecureRandom | cryptographically strong unpredictability | tokens, keys, passwords |
RandomGenerator.of(name) | named modern algorithms, same interface | picking an algorithm deliberately |
- A seeded
Randomreplays exactly: seed 42 gives the same numbers on every machine running the same JVM algorithm. - Never use `Random` for security. Predictable sequences mean guessable tokens; that is what
SecureRandomexists for. RandomGenerator(JDK 17 and later) unifies the family behind one interface;RandomGenerator.of("L64X128MixRandom")names an algorithm instead of a class.
The odd-tools playbook
When the main collections do not fit the shape:
- Flags over a dense range of ids:
BitSet, and letcardinalitydo the counting. - Building a delimited text from pieces:
StringJoinerorString.join, never a manual separator flag. - Needing a unique id without a coordinator:
UUID.randomUUID. - Needing repeatable randomness: seed a
Random; needing secrecy:SecureRandom; needing speed under threads:ThreadLocalRandom. - Reach for one of these only when the shape of the data matches; otherwise the standard collections stay first choice.
Every tool here answers a shape. Bits for dense flags, joiners for text, UUIDs for identity, randomness with an explicit promise. Naming the shape is the whole skill.
java.util is more than collections
BitSet packs dense flags with set algebra built in. StringJoiner and String.join remove a class of separator bugs. UUID.randomUUID produces coordination-free identifiers, cryptographically seeded. The Random family splits by promise: seeded for reproducibility, ThreadLocalRandom for speed, SecureRandom for secrecy, RandomGenerator for named algorithms. Each tool exists because some data has a shape the list and map contract does not match.
Interview angles
Set<Integer> or BitSet for tracking seen ids?+
Sparse ids: Set, because a BitSet sized by the largest id allocates for the whole range below it. Dense, bounded flags: BitSet wins on memory (one bit per id) and gains bulk operations.
The crossover is the density and the ceiling. Ten known ids in a range of a billion: Set. Every id up to a few million with membership checks: BitSet, where cardinality, nextSetBit and and/or/xor run in word-sized steps.
Common misconception: That BitSet is the old, primitive option. It is the specialized option for dense bits, with an API no Set can match.
Follow-up: What does nextSetBit save you?
How do you build "a, b, c" from three pieces?+
String.join for a one-shot join, StringJoiner when the pieces arrive one at a time or need a prefix and suffix.
The manual loop with a boolean first flag is the pattern both replace, and it is a classic source of doubled or missing separators. StringJoiner also merges partial joins, which fits recursive and streaming producers.
Common misconception: That concatenation in a loop is equivalent. It is equivalent only after you have separately solved the separator, prefix and suffix problems.
Follow-up: Where do you meet String.join in real pipelines?
Is UUID.randomUUID a fair id strategy?+
Yes for uniqueness without coordination: it is version 4, 122 random bits from a cryptographically strong source, and collisions are negligible at any realistic scale.
Two properties matter in review: it is not ordered (no range scans or batching by time), and it costs 36 characters when stored as text, so databases often store the 16 bytes. When ordering matters, version 4 is the wrong UUID.
Common misconception: That random UUIDs can collide under load. The birthday math leaves collisions unobservable at practical volumes; the real trade is ordering and storage size.
Follow-up: What type of id orders by creation time?
Random, ThreadLocalRandom, SecureRandom: when each?+
Seeded Random for reproducible sequences, ThreadLocalRandom for fast throws in parallel code, SecureRandom for anything an attacker must not predict.
Random is a linear generator: fine for games and simulations, catastrophic for tokens. ThreadLocalRandom removes the shared seed contention that makes Random slow under many threads. SecureRandom draws from OS entropy and is slower by design.
Common misconception: That all three are interchangeable because the API looks the same. The promise behind the numbers is what differs.
Follow-up: What did JDK 17 add on top of all three?
What is RandomGenerator and why does it exist?+
A single interface over all random generators, plus a factory of named algorithms such as L64X128MixRandom: one type to program against, algorithms chosen deliberately.
It lets methods accept any generator without caring about the implementation, mirroring the collections philosophy: interface at the seams, implementation chosen at one line. The named algorithms have documented quality properties, which older Random subclasses never promised.
Common misconception: That it replaces SecureRandom. SecureRandom remains the tool for unpredictability; RandomGenerator unifies the non-cryptographic family and some of its methods.
Follow-up: Which one would you inject into a simulation class, and why?