File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes implementing the hash map Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply 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: 64
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
Saloon Keeper

Joined: Oct 27, 2005
Posts: 18365

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
How To Ask Questions How To Answer Questions
 
 
subject: implementing the hash map
 
Threads others viewed
Can Someone tell me whats wrong with this RLE simple code???
How to Split and count the character
to find a string in a file
Need help with EOFException error
Error printing out from a read in file.
Two Laptop Bag