Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Varuna Seneviratna
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
 
Henry Wong
author
Marshal
Pie
Posts: 21002
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic