Search code examples
javatreemap

TreeMap does not compare every element in the map


This is a general question to ask: I am writing a custom comparator in TreeMap to compare a custom class A (defined by myself). What I found is that when I keep adding key-value pair into the treemap, the newly added key does not compare every key in the treemap, instead it only compares a few keys at the bottom and skips some keys at the top. So that there are duplicate keys in the treemap.

Does anyone have this question before? Again this is a general question to ask, the code especially the dataset used to test is not open to public.


Solution

  • This is the expected behavior. The TreeMap class is implemented as a binary search tree. As such, it will only need to access up to the base-2 logarithm of the total number of nodes. You can see this behavior for yourself in the TreeMap.java implementation, where the code determines whether it needs to access the left or right child node. For details, check out the put() and get() method implementations.