This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes HashMaps Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "HashMaps" Watch "HashMaps" New topic


Komal Arora
Ranch Hand

Joined: Sep 30, 2010
Posts: 91

just a simple question: Do hashMaps allow duplicate keys? can there be distinct keys but duplicate values? is Hashmap sorted or ordered?

Jelle Klap

Joined: Mar 10, 2008
Posts: 1756

Hey, that's three questions! ;)
The java.util.HashMap implementation of the java.util.Map interface does not allow duplicate keys (it does allow the null key), distinct keys can map to duplicate values and it is neither ordered nor sorted. If you are looking for a sorted Map implementation you should have a look at java.util.TreeMap.

Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Ram Narayan.M
Ranch Hand

Joined: Jul 11, 2010
Posts: 247

1.) Existing key-value pair will be replaced by new comer key-value pair, if keys are same... So, You will lose the previous value...

2.) Yes...

3.) Its neither sorted nor ordered... But implicitly it takes the key-value pair based on hashcode in ascending order... So you cant expect them in an order...

SCJP 6 [SCJP - Old is Gold]
Komal Arora
Ranch Hand

Joined: Sep 30, 2010
Posts: 91

Lol yeah Jelle, one question led to another and in no time one became three!

Jelle and Ram, Thanks for the explanation
I agree. Here's the link:
subject: HashMaps
Similar Threads
duplicates in collection
sorting a array
Memory size and access
HashTable / HashMap..?
A dumb question