• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

implementing the hash map

 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a code where i count number of occurences of each letter. For performance sake i want to convet the same using hash map. Can any of you help me on how to implement hash map?
Here is my code
 
Sheriff
Posts: 22781
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

sahana mithra wrote:[/code]


First of all, a small tip. You now are copying the entire String into a new char[] (that's what toCharArray() does). You can instead write the same without this copying:

Now, back to the problem. You need a Map<Character,Integer>. The keys will be the characters, the values the number of occurrences. When you encounter a character you must:
1) retrieve its old value.
2) increase the old value. Keep in mind that for the first occurrence of the character there will be no old value so it will be null. I'll leave it up to you to find an appropriate new value.
3) put back the new value into the map, thereby overwriting the old value.

You can use auto-boxing to make life easier for you, as long as you remember that possible null value - unboxing null will lead to a NullPointerException.

As for the Map type to use, a LinkedHashMap will preserve the insertion order where a TreeMap will sort the keys.
 
I guess I've been abducted by space aliens. So unprofessional. They tried to probe me with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic