0

As in HashMap there are buckets internally to hold key value pairs.

For the case of keys which have same hash code.

For instance hash code of "abcdef" and "abcdfG" is same.

map.put("abcdef", 1);
map.put("abcdfG", 2);

When they are put in hash map Entry object gets created where both are placed in same bucket and next of one Entry points to other one.

The question is how will get behave ? When we do map.get("abcdef"); will it give 1 or 2

2
  • 1
    it will first use hashCode to resolve bucket and then it will traverse through binary tree to get to exact key and then it will get value once exact key is found Commented Jun 22, 2015 at 17:12
  • Why didn't you try it out or read the javadoc? That's not only 1 but 2 obvious and simple ways of getting the answer yourself. Commented Jun 22, 2015 at 18:07

3 Answers 3

1

map.get("abcdef") will return the correct value (1), since it will use equals method to compare each key in the bucket (that matches the hashCode of the key) to the given key, until it finds an exact match.

Sign up to request clarification or add additional context in comments.

Comments

1

The internal buckets are only used by java to help reduce the number of items it needs to search. You can push everything in the same bucket (with a different key). The result is just your program will be slower.

Comments

1

it will first use hashcode() to resolve bucket and then it will traverse through balanced tree to get to exact key and then it will get value once exact key is found

depending on the version of runtime you use, it would be LinkedList or Balanced tree

http://openjdk.java.net/jeps/180

6 Comments

Binary tree? Singly linked list, no?
@Boris sorry balanced tree, That was replaced by balanced tree with openjdk.java.net/jeps/180
Interesting - didn't know they had changed the implementation.
Thanks Jigar can u please provide me a link to detailed explanation of the fact of linked list or balanced tree, how it gets created during the time of collision and other in depth details related to this.
|

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.