[crackmonkey] [scheide@usfca.edu: Adding one to a java hashtable]
Seth David Schoen
schoen at uclink4.berkeley.edu
Wed Dec 23 21:20:33 PST 1998
Nick Moffitt writes:
> ----- Forwarded message from Eric Scheide <scheide at usfca.edu> -----
>
> Ok start thinking java.
>
> words is the hash
> w is the key (a word)
> Look at the stupid crap you have to do to increment the Integer object.
> There must be an easier way. Far as I know a hash table has to take an
> object as the value so you cant just use an int number. It must be an
> Interger object. Seems silly.
>
> if (words.containsKey(w)) {
> words.put(w,new Integer(((Integer)words.get(w)).intValue()+ 1));
> }
Well, you're not really using OOP that well to abstract out the nature of
this operation.
If you can store any kind of object in a hash, an assumption that seems
reasonable but whose correctness I'm really not positive of, you could do
public class incrementableInPlaceInteger{
int number;
public incrementableInPlaceInteger(){
// Constructor
number = 0;
}
public int value(){
return number;
}
public void increment(){
number += 1;
}
}
OK, now you store a "new incrementableInPlaceInteger()" in the hash.
When you want to increment one, you do
if (words.containsKey(w)) {
((incrementableInPlaceInteger)words.get(w)).increment();
}
which is fully 8 bytes shorter than your version. Or you can make a new
"incrementableInPlaceIntegerHash" descended from hash (which is then a hash
whose get method has a built-in typecast to force the value returned by the
get method into an incrementableInPlaceInteger). Once you've written that
class, you can omit the typecast when actually making use of one:
if (words.containsKey(w)) {
words.get(w).increment();
}
Another option would be to write a hash class with a conditional get, or a
getOrInsert, or even a big method to do this whole thing:
words.getAndIncrementOrInsertWithIntegerValueInitializatedToZero(w);
-- by which time you've rewritten your Perl hash. :-)
But hey, you'd have written a pretty nice long method name...
(The parsing of "pretty nice long method name" is intentionally ambiguous.)
--
Seth David Schoen L&S '01 (undeclared) / schoen at uclink4.berkeley.edu
He said, "This is what the king who will reign over you will do." And they
said, "Nay, but we will have a king over us, that we also may be like all the
nations." (1 Sam 8) http://ishmael.geecs.org/~sigma/ http://www.loyalty.org/
=====================================================================
To unsubscribe, send a message to majordomo at zork.net saying
"unsubscribe crackmonkey" in the body of the message.
More information about the Crackmonkey
mailing list