• Post Reply Bookmark Topic Watch Topic
  • New Topic

adding value to TreeMap  RSS feed

 
Tom Mordon
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a TreeMap:


In the method if the token is found I'm supposed to add to the List but the compiler does not like my code. How can I add the tokenOccurence to the list in the TreeMap? This one area has been stumping be for hours.

 
Greg Charles
Sheriff
Posts: 3015
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Tom,

Welcome to JavaRanch! First, a quick nag: please use code tags when posting code. There's a Code button above the edit window, which makes it really easy to do.

Now, TreeMap, like all maps lets you add a key, value pair and the method is called put(key, value). There is no TreeMap.add() method, so what you've shown us wouldn't even compile. I'm not completely sure what you are trying to do, but if you want to add an integer like tokenOccurence to a map, you have to covert it to an Object, like by calling "new Integer(tokenOccurence)".
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tom Mordon wrote:In the method if the token is found I'm supposed to add to the List but the compiler does not like my code. How can I add the tokenOccurence to the list in the TreeMap? This one area has been stumping be for hours.

I'm not quite sure exactly what it is you're trying to do. Are you trying to count the number of times a particular token appears in a piece of input?

If so:
(a) You don't need a List.
(b) You need a counter of some sort, and unfortunately, Integer isn't the ideal class because it's immutable.

If indeed that is what you want to do, my suggestion would be to try a TreeList<String, AtomicInteger> (AtomicInteger is mutable).

Winston
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can’t add directly to the set of keys. I would suggest you cheat, but I won’t tell you which section of the Java™ Tutorials you will find a very similar example in.
The problem about Integer (as you already know) is that it is immutable. But you can’t store ints in Collections. So you have to use boxing and unboxing if you want to do any arithmetic. You will have to use the atomic version if you are multi-threading.
 
suraj august
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!