So im trying to keep track of how many times each key on the keyboard is pressed, so I need something like a TreeMap that is ordered by variables. Anyone know a good data structure that takes care of this?
Asked
Active
Viewed 462 times
2
-
What do you mean ordered? You need to specify what kind of order you're talking about here. – ColinD Nov 22 '10 at 01:22
-
Lets say its a TreeMap
. It would be ordered from highest to lowest by the value, instead of the key. – Rahat Ahmed Nov 22 '10 at 16:54 -
Seems similar to [this](http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java). – Dmitri Nov 22 '10 at 00:42
2 Answers
1
Why not make an int array where key value corresponds to array index? As long as you aren't supporting beyond e.g. standard ASCII, this should be reasonable.

Armand
- 23,463
- 20
- 90
- 119
-
That wouldn't be ordered. I'd probably make a method for that but i wanted to see if there was an easier way first – Rahat Ahmed Nov 22 '10 at 00:50
-
Lets say its a TreeMap
. It would be ordered from highest to lowest by the value, instead of the key. – Rahat Ahmed Nov 22 '10 at 16:52 -
1
Why not use a TreeMap
? It has the ability to order its elements using a Comparator
. You can define a class that implements Comparator
which will determine which of two char
's is "greater" than the other, thereby providing a means of ordering. I think String
has a method for doing just this; your Comparator
will just need to convert the char
's into String
's and then return the value of String.compare
.

AniDev
- 1,569
- 1
- 18
- 21
-
I tried this, but i get a NullPointerException when my TreeSet gets two objects to compare – Rahat Ahmed Nov 22 '10 at 03:55
-
I figured out why, Java doesn't pass TreeMaps by reference so the map inside my comparator isn't the same as the one in my main code. – Rahat Ahmed Nov 22 '10 at 16:54