File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Duplicate Keys on hashtable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Duplicate Keys on hashtable" Watch "Duplicate Keys on hashtable" New topic

Duplicate Keys on hashtable

rudresh kumar
Ranch Hand

Joined: Jan 04, 2006
Posts: 83

I have a problem in putting duplicate keys in hastable.

In my application immediately after the user logs in successfully, i put his userid and sessionid in hashmap.

Let me explain the problem
1.user X logs in
2.userid and session id are put in hashmap
3.hashmap size is 1
4.again user X opens a new window and logs in (other window is still open)
5.again now the same userid but with different sessionid(as it is new browser) has been put in hashmap has over written that had happend in 2, size of the hashmap is still 1.end result, same user id but session id of 4/5 is put in. user Y logs in that userY's id and sessionid is put in hashmap,size increases to 2

can some one explain me what is happening in 5,why it is getting overwritten, We can insert duplicate keys in hashmap, Please help me in solving this.

Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
That's the expected behavior, according to the documentation:

A map cannot contain duplicate keys; each key can map to at most one value.


put(...) ... If the map previously contained a mapping for this key, the old value is replaced by the specified value.

The behavior you seem to want is provided by a MultiMap:

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I agree. Here's the link:
subject: Duplicate Keys on hashtable
It's not a secret anymore!