Video in progress
What structure is inside TreeMap, and what happens if the comparator is inconsistent with equals or a null key shows up?
TreeMap is a red-black tree: put, get and remove are O(log n), and the tree height does not exceed about 2·log n. Keys are compared only with compareTo/compare, so two keys for which the comparator returns 0 become one key, and with natural ordering a null key throws an NPE.
📖 Answer
Every node holds a key, a value, left and right children, a parent reference and a color, so it is bigger than HashMap.Node, about 40 bytes. After an insert or removal, the tree rebalances with rotations and recoloring. That is why even the worst case is O(log n): the "everything landed in one bucket" situation of HashMap doesn't exist here.
get goes only through the comparator, and equals and hashCode are never called at all. This leads to unexpected results:
Map<String, Integer> m = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
m.put("Admin", 1);
m.put("ADMIN", 2); // not a new entry: the value of "Admin" became 2
m.keySet(); // [Admin] — the key stays in the form it was first put in
Sometimes that is exactly what you want (a map like this is handy for HTTP headers). Sometimes it is a bug: if the comparator looks at only one field, other entries get silently overwritten.
About null: with natural ordering, put(null, ...) throws an NPE even on an empty map, because the first put calls compare(key, key) to check the key type. If you need null, pass a comparator:
new TreeMap<String, Integer>(Comparator.nullsFirst(Comparator.naturalOrder()));
One more practical point: if a field of the key that affects the comparator changes while the key sits in the map, the tree order is broken and lookups go down the wrong branch. Then containsKey returns false for some keys, and iteration comes out unordered.
Sign up to mark studied questions and save your progress.