2

Treemap uses red-black tree internally for implementation. Treemap takes Comparable<> or Comparator<> as parameter which red-black tree uses for inserting data in binary search tree.

From java 8, hash map has started using red-black tree once threeshold of linklist is reached in case of hash collision. My question is, for custom class I implement equals() and hashcode() but not comparator and use this custom class as key in hashmap then how red black tree will work without comparator in case of hash collision.

3
  • 3
    You might read points one and three of this answer Commented Jun 24, 2021 at 7:33
  • @Holger If the keys are not Comparable and when we have hash collisions, then does it use a combination of binary search and linear search? Binary search for the keys with distinct hash code and use linear search for those keys that have the same hash code? Commented Jun 24, 2021 at 7:44
  • 1
    Yes, that’s how the lookup works. As discussed in this Q&A, it will still build a binary tree for those keys, but for the subtree where all keys have the same hash code and are not comparable, the search has to run through both branches. Commented Jun 24, 2021 at 7:55

1 Answer 1

1

Summarizing my understanding for other viewers of this question:

  1. If there is bucket collision(which is not necessarily hash code collision), then binary tree comes in picture and searches for hashcode
  2. if hash code is same then it will rely on comparable implementation of key of hashmap.
  3. If key has not implemented comparable then both(left and right) branches of tree will be traversed in this scenario.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.