Results 1 to 5 of 5
Thread: summing value within Hashtable
- 09-23-2010, 12:32 AM #1
Member
- Join Date
- Aug 2010
- Posts
- 8
- Rep Power
- 0
summing value within Hashtable
Hello,
I'm having problem trying to figure out how to use Hashtable data structure. I'm reading names and number of occurrences for that name from text files. I'm using name as key and number of occurrences as value. If the name exist in Hashtable I want to sum the two values and store it back in Hashtable. How do I do that? Here is where I'm at (Bear in mind I'm very new to programming):
Java Code:public class HashTableImplementation { double sum = 0; Hashtable hashList = new Hashtable(); public HashTableImplementation() { hashList = new Hashtable(); } public void addToHasTable(String name, double weight) { if (!hashList.containsKey(name)) hashList.put(name, weight); else { //sum weights for that name } }
Last edited by dc0m; 09-23-2010 at 12:44 AM.
- 09-23-2010, 12:43 AM #2I want to sum the two values and store it back in Hashtable
If the key is there, get the value, add the new value to the existing one and put that object back.
You are using the autoboxing feature of the compiler to put your values in the hashtable. The put method takes two objects. It does NOT take a primitive like a double. The compiler is wrapping your double into a Double.
- 09-23-2010, 12:59 AM #3
Member
- Join Date
- Aug 2010
- Posts
- 8
- Rep Power
- 0
Thanks for fast response.
I managed to do that, by doing this.
Java Code:sum = weight + Double.parseDouble(hashList.get(name).toString()); hashList.put(name, sum);
Let's say I have Mary, 33, and then I get another Mary with 40. I want to add to "Mary" (which has value 33) value 40. The result would be one Mary,73. But istead I get two Marys, one with 33 and one with 73. Where am I making mistake?
Thanks again.Last edited by dc0m; 09-23-2010 at 01:03 AM.
- 09-23-2010, 01:10 AM #4
I don't know how you can get two keys = Mary.
Can you post the code.
Java Code:sum = weight + Double.parseDouble(hashList.get(name).toString());
- 09-23-2010, 01:17 AM #5
Member
- Join Date
- Aug 2010
- Posts
- 8
- Rep Power
- 0
[SOLVED]summing value with Hashtable
Never mind, that actually worked, there was actually totally different reason why it printed out two Marys.
Thanks a lot friend.
"Putting all the code in one statement is a poor way to do it. "
What is the right way to do it?Last edited by dc0m; 09-23-2010 at 01:31 AM.
Similar Threads
-
Help with summing series
By xplsivo in forum New To JavaReplies: 8Last Post: 11-23-2009, 08:37 PM -
hashtable
By vijayabaskar in forum Java ServletReplies: 0Last Post: 04-06-2009, 09:20 AM -
hashtable
By vijayabaskar in forum Advanced JavaReplies: 2Last Post: 04-06-2009, 09:05 AM -
Hashtable
By angelicsign in forum New To JavaReplies: 6Last Post: 02-05-2009, 05:30 PM -
Hashtable example
By Java Tip in forum Java TipReplies: 0Last Post: 02-15-2008, 09:43 AM
Bookmarks