Using the last digit as hash would allow a hashmap to have exactly 10 buckets for chaining the values to save.
Norm Radder wrote:Using the last digit as hash would allow a hashmap to have exactly 10 buckets for chaining the values to save.
This is not true. Hash maps perform their own rehashing operation on the hash code of an object to spread them out as much as possible. Even if all objects return the same hash code, a small hash map will still place most of them in a separate bucket.
small hash map will still place most of them in a separate bucket.
Not always possible. If the hashmap has 10 buckets and the user adds 100 items to it, then ideally each bucket would have 10 elements.
I'm talking about the idea of hashmaps in general, not the java class.
How many different String values is it possible to have? Well, first of all the length of a String object can be anything from zero all the way up to 2^31 - 1. And each character in a String can be any of 65536 different characters. I'll let you figure out how many different Strings there can be, but if you want to skip that step let me just say that the number you get is incredibly humongous.
And how many different hash codes can that incredibly humongous number of Strings have? Well, a hash code has to be a Java int, so there can only be 2^32 different hash codes. That number is a lot less than "incredibly humongous" and so it follows that many, many different String objects must have the same hash code. (Look up Pigeonhole Principle if that doesn't strike you as immediately obvious.)
Arun Singh Raaj wrote: If two objects have the same hash code, they may or may not be equal
Its depend on your requirement in application..
Like, i have tested with team pairs where i want same hash code for the object having same pair..
here, for Pair(a,b) and Pair(b,a) will give you same hash code..
where as default implementation of Pair class will give different hash code for Pair(a,b) and Pair(b,a)
and you can override you equals method also as per your requirement in application.
Hope, you will get clarification