Forums Register Login

adding value to TreeMap

+Pie Number of slices to send: Send
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.

+Pie Number of slices to send: Send
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)".
+Pie Number of slices to send: Send
 

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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
My name is Inigo Montoya, you killed my father, prepare to read a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 3645 times.
Similar Threads
Can I have a list in tree map?
treemap
treemap
String Tokenizer
How to add elements from a file into an Array List
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 15, 2024 23:23:30.