Hidden Java Tree Map Insights

Apart from knowing basic facts about tree map below details can help you answer some basic interview question

  1. TreeMap works on RedBlack Algorithm which is basically a self balancing binary tree.
  2. Since it uses binary tree hence the time complexity of operations are O(logn).
  3. Overriding hash and equals function are mandatory if we are making a custom class a key in tree map ??
    Answer is NO
    Tree Map uses compareTo function for inserting elements and sorting them.
    Overriding equals and hascode wont make impact except for taking some lines of code in your class
  4. So the custom class shoud implement comparable interface or during map creation one should provide the comparator
    What if i dont implement comparable or i dont provide comparator during tree creation??
    Unlike hashmap which keep on stroing duplicate keys if we dont override hashcode or equals thats not the case with treemap
    ClassCastException will be thrown if comparable or comparator is not provided
  5. Unlike other DS in trees we dont provide size during creation since it self balances itself
Comments (0)