Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Problems using TreeMap to detirmane word frequency

807580Feb 8 2010 — edited Feb 9 2010
Hi!

I'm using Java TreeMap to determine the amount of times words appear in a text file, however, I seem to run into a little problem:

The Algorithm is as follows: Simply check if the words already exists in the tree(The words themselves are used a keys), then get the value(integer) and increase this value. As the .put statement only updates the value associated with the key, it shouldn't store double values... right?

Although this is my question, it still isn't the problem. The problem is the following: To update the value, I simply want to use the ‘.get’ statement. Java API specifically states the following :

“get(Object key)
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.”

So, getting it as an int, I should be able to just add to this right? NO! I get a compatibility error, stating that I can’t assign Java.lang.Object to int. Please Help!
Here’s my code:

Map list = new TreeMap();

if(list.containsValue(word))
{
//assign integer to current word's value
//int count used
wcount = list.get(word) + 1; //Error: operator + cannot be applied to java.lang.Object,int
list.put(word, wcount);

//however, this will work, but you can't cast Objects to ints:
//ocount is now object
Object ocount = list.get(word);

}
else
list.put(word, 1);
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 9 2010
Added on Feb 8 2010
6 comments
727 views