aspose file tools*
The moose likes Java in General and the fly likes implementing the hash map Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "implementing the hash map" Watch "implementing the hash map" New topic
Author

implementing the hash map

sahana mithra
Ranch Hand

Joined: Oct 26, 2010
Posts: 72
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

Joined: Oct 27, 2005
Posts: 19718
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: implementing the hash map