Skip to content
Tutorials Center
My learning

Topics

Lesson 92 of 201 ยท Collections

EnumMap, EnumSet, IdentityHashMap, WeakHashMap and BitSet

Learn the specialized Java collections - EnumMap and EnumSet for enum keys, IdentityHashMap for reference equality, WeakHashMap for GC-friendly maps and BitSet for flags.

HashMap, HashSet and ArrayList are excellent defaults, but "default" means "good at everything, best at nothing in particular". The JDK also ships a handful of collections that are designed for one specific situation and beat the general-purpose classes there, often by a wide margin.

This lesson covers five of them: EnumMap and EnumSet, which turn enum keys into tiny, fast arrays and bit masks; IdentityHashMap, which compares keys with == instead of equals; WeakHashMap, whose entries disappear when nobody else uses the key; and BitSet, a compact, growable array of bits. For each, you'll see what it's for, a small example, and when not to use it.

EnumMap: a map with enum keys

When every key is a constant of one enum (days of the week, order states, card suits), use EnumMap instead of HashMap. Because the set of possible keys is fixed and each constant has an ordinal() (0, 1, 2, ...), an EnumMap is really just an array indexed by ordinal. No hashing, no buckets, no entry objects.

Java Counting orders by status

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What you get from EnumMap:

  • Order: iteration always follows the enum's declaration order, no matter the insertion order. That makes output predictable without sorting.
  • Speed and memory: get and put are an array access. It's typically faster than HashMap and much smaller.
  • Type safety: the constructor takes the enum's class (Status.class), and the map rejects anything else, including null keys (null values are allowed).

You can also create one by copying another map, as with labels above; the source must be non-empty or an EnumMap itself, so the enum type can be determined. With streams, use Collectors.groupingBy(Order::status, () -> new EnumMap<>(Status.class), Collectors.counting()) to group straight into an EnumMap (Collecting Stream Results).

EnumSet: a set of enum constants

EnumSet stores enum constants as bits in a long: bit 0 for the first constant, bit 1 for the second, and so on (enums with more than 64 constants use a long[]). contains is a single bit test, and addAll/retainAll between two EnumSets are single bitwise operations. It's the modern, type-safe replacement for int flags like READ | WRITE (see Bitwise and Shift Operators).

You create one with static factory methods rather than new:

Factory Contents
EnumSet.of(a, b, ...) the given constants
EnumSet.noneOf(Type.class) empty
EnumSet.allOf(Type.class) every constant
EnumSet.range(from, to) from to to, both inclusive, in declaration order
EnumSet.complementOf(set) every constant not in set
EnumSet.copyOf(collection) a copy
Java Opening hours and file permissions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Like EnumMap, an EnumSet iterates in declaration order and rejects null. Notice that range includes both ends, unlike subList or TreeSet.subSet. DayOfWeek is a JDK enum from Dates and Times, so it works with these collections directly.

If a field or parameter is "a set of options" from an enum, make it an EnumSet, not a boolean per option or an int bit mask. EnumSet.of(Style.BOLD, Style.ITALIC) reads better than BOLD | ITALIC, can't hold invalid bits, and is just as fast. Enums covers enums themselves.

IdentityHashMap: keys compared with ==

Every other general-purpose map compares keys with equals and hashCode. IdentityHashMap deliberately breaks that rule: it compares keys with == (the same object in memory) and hashes them with System.identityHashCode. Two different objects with equal contents are two separate keys.

Java Equal but not identical

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

That's almost never what you want for normal data, which is why the class's own documentation calls it a special-purpose map. Its legitimate uses are in code that walks object graphs, where the question really is "have I seen this exact object before?":

  • Deep copying and serialization: remember which original objects have already been copied, so shared references and cycles are copied once.
  • Cycle detection: a structure that contains itself (directly or indirectly) would loop forever without an identity-based "visited" set.
  • Attaching data to objects whose equals you can't trust or don't want to call (for example, mutable objects or proxies).

For an identity-based set, use Collections.newSetFromMap(new IdentityHashMap<>()):

Java Detecting a cycle in linked nodes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

IdentityHashMap also has an unusual implementation: it stores keys and values side by side in a single array (open addressing) instead of buckets of entry objects, which makes it compact. It allows null keys and values, and it isn't thread-safe.

WeakHashMap: entries that disappear

Normally, putting an object into a map keeps it alive: as long as the map is reachable, the garbage collector can't free the key. A WeakHashMap holds its keys through weak references instead. If the map is the only thing still referring to a key, the garbage collector is free to reclaim that key, and the entry is removed from the map automatically.

The idea is to attach extra data to objects that someone else owns, without keeping those objects alive longer than their owner wants:

Java Entries vanish after their keys are collected

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

When you run this, the entry for "ben" is normally gone after a garbage collection, while "ana" stays because the variable alive still refers to its key. The output depends on the garbage collector, though. System.gc() is only a hint, which is why the example asks several times. Never write logic that depends on exactly when an entry disappears. Memory and Garbage Collection explains reachability and weak references in detail.

Things that trip people up with WeakHashMap:

  • Only keys are weak. If a value refers to its own key (directly or indirectly), the key stays strongly reachable and the entry never disappears.
  • Keys must not be "everlasting" objects. String literals, small cached Integers and enum constants are kept alive by the JVM, so entries with those keys never go away.
  • It still uses equals. Keys are matched with equals/hashCode like a HashMap, so two equal keys are the same entry. A lookup with an equal key finds the entry, but only the original key object keeps the entry alive: holding on to an equal copy doesn't.
  • It's not a cache. Entries vanish when the key becomes unreachable, not when memory is low or when an entry is old. For real caches, use a size-limited LRU map (LinkedHashMap and LinkedHashSet) or a caching library.

WeakHashMap is not thread-safe. Its classic users are frameworks and libraries that need to associate data with classes, class loaders or listener objects they don't own.

BitSet: a growable array of bits

A BitSet is a sequence of bits, indexed from 0, that grows as needed. Each bit is either set (true) or clear (false), and it costs one bit of memory, compared with 16 bytes or more for each Boolean in a Set<Integer> or List<Boolean>. A million flags fit in about 125 KB.

Method What it does
set(i), set(from, to) set bit i, or the range from (inclusive) to to (exclusive)
clear(i), flip(i) clear or toggle a bit
get(i) true if bit i is set
cardinality() how many bits are set
nextSetBit(i), nextClearBit(i), previousSetBit(i) find the next set or clear bit; nextSetBit returns -1 when there are no more
length() index of the highest set bit + 1
and(other), or(other), xor(other), andNot(other) combine bit sets in place
stream() an IntStream of the set indexes
Java Seat reservations as bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

toString() lists the indexes of the set bits in braces. The nextSetBit loop at the end is the standard way to visit every set bit; booked.stream() does the same as a stream.

A classic use is the sieve of Eratosthenes: start with every number marked as a candidate prime, then cross out the multiples of each prime you find. A BitSet makes the marks cheap:

Java Sieve of Eratosthenes with a BitSet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Choose BitSet when you have many small non-negative integers or flags: visited markers for graph nodes numbered 0 to n, Bloom filters, feature flags per user ID, or a set of character codes. For a set of enum constants, EnumSet is the type-safe choice and uses the same bit trick internally. BitSet is not thread-safe.

Quick reference

Class Use it when Key behavior
EnumMap keys are constants of one enum array by ordinal, declaration order, no null keys
EnumSet a set of constants of one enum bit vector, declaration order, range is inclusive
IdentityHashMap you need "same object", not "equal object" == and identityHashCode
WeakHashMap data attached to objects you don't own entries vanish once the key is unreachable
BitSet many flags indexed by small integers one bit per flag, fast bulk operations

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Enum Size { S, M, L, XL }. You put L, then S, then XL into an EnumMap. In what order are the keys printed?

    EnumMap always iterates in the enum's declaration order (by ordinal), regardless of insertion order.
  2. 2. What does EnumSet.range(Size.M, Size.XL) contain?

    EnumSet.range includes both endpoints, unlike most Java range methods, which exclude the end.
  3. 3. Two records are equal but are different objects. You put both into an IdentityHashMap as keys. What is the map's size?

    IdentityHashMap compares keys with ==, so two distinct objects are two keys even when equals says they are equal.
  4. 4. Which key would keep its WeakHashMap entry from ever being removed?

    Enum constants stay reachable for the whole life of their class, so the garbage collector never clears them and the entry stays forever.
  5. 5. After BitSet b = new BitSet(); b.set(2); b.set(5, 8);, what is b.cardinality()?

    set(2) sets one bit and set(5, 8) sets bits 5, 6 and 7 (the end is exclusive), so four bits are set.

Summary

  • EnumMap is an array indexed by enum ordinal: fast, compact, and always in declaration order.
  • EnumSet stores enum constants as bits and replaces int flags; build it with of, noneOf, allOf, range (inclusive) and complementOf.
  • IdentityHashMap compares keys with ==; use it (or an identity set from Collections.newSetFromMap) when walking object graphs or detecting cycles.
  • WeakHashMap lets entries disappear once their keys are no longer used elsewhere; it's for attaching data to objects you don't own, not for caching.
  • BitSet stores many flags at one bit each, with cardinality, nextSetBit and fast and/or/andNot.

Next: Legacy Collections: Vector, Stack, Hashtable and Enumeration, where you'll meet the collections Java started with and the modern classes that replace them.