Two Laptop Bag*
The moose likes Beginning Java and the fly likes How to get the number of entries in a HashMap, including the duplicate entries? 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 » Java » Beginning Java
Bookmark "How to get the number of entries in a HashMap, including the duplicate entries?" Watch "How to get the number of entries in a HashMap, including the duplicate entries?" New topic
Author

How to get the number of entries in a HashMap, including the duplicate entries?

Varuna Seneviratna
Ranch Hand

Joined: Jan 15, 2007
Posts: 167


In the above class I have added a duplicate entryincluding that there should be four entries, But the size() returns 3, Is there a way to get the total number of entries including the duplicate entries

Varuna


Varuna Seneviratna
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18546
    
  40

including that there should be four entries, But the size() returns 3, Is there a way to get the total number of entries including the duplicate entries



Unfortunately, hashmaps don't support duplicates. The reason it is reporting three entries is because there is only three entries in the map.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Mark Vedder
Ranch Hand

Joined: Dec 17, 2003
Posts: 624

If it helps any, keep in mind that the HashMap's put method will return the previous value associated with the key (returning null if there was no value for the key or if the value for the key was null). In some situation this can be useful.

For something like a phone book where a key (a person's name) is very likely to have duplicate entries, I would use a double collection. Make your PhoneBook Map use the name for the key and another collection as the value. That collection would hold the phone numbers for that person. You could simply use a set which would prevent multiples of the same phone number; or use another Map with the key being the phone number type, "work", "home", "cell", etc. So you would end up with one master collection which holds a number of other collections.

I hope that helps.
 
wood burning stoves
 
subject: How to get the number of entries in a HashMap, including the duplicate entries?
 
Similar Threads
Why is the ArrayList Object not Created Befor assigning values from ArrayList loc
For your advice on the Calulator so far developed
I would like to have your advice about the way I have designed the application
What am I doing wrong?
Java Clarifications..help needed