• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

implementing the hash map

 
sahana mithra
Ranch Hand
Posts: 72
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
Rob Spoor
Sheriff
Pie
Posts: 20369
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic