I have one hash map. I’m storing 12 different key,values pairs in it.
The first 8 values are stored fine, but when I try to put the 9th value it overwrites the old value. But the size increases.
If I try to get the old values, I get nulls. I have also checked the hash map table. Only 8 values are there. The old values are overwritten.
here have only 7 values but size is 9 . how it’s possible ?
What could I be doing wrong?
As for the size=9 but only 7 values in the table, you are misunderstanding the internal workings of the
HashMap. All values are not stored in the top-level table. The table is more like “buckets” that store entries grouped by certain hashcode ranges. Each “bucket” holds a chain of linked entries so what you are seeing in the table are just the first entries in each particular range chain. Thesizeis always correct though, in terms of total number of entries in the map.As for entries overwriting eachother, that happens only when you put en entry with a key that is identical (hashCode and equals) to en existing entry. So you are either adding with an existing key, or you are adding with
nullas key (null is permissible as key, but you can only have one entry with the key null).Check your code, are you adding with
nullkeys? If you are using instances of a custom class (one you created yourself) as key, have you implementedhashCode()andequals()according to the specifications (see http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#hashCode%28%29)? Are you making sure that you are really using unique keys for all 12 put operations?