Reputation: 8380
I'm making a program where a hashing of a string is used to decide a write location in a file. Here's how the location is calculated:
private long getWriteLocation(String s){
long hash = s.hashCode()%FILESIZE;
hash = hash*FILEENTRYSIZE;
return hash;
}
the problem with this is that hashCode()
can produce negative values. This leads to a crash since I'm using the output of the function as a write location to file:
ptr = getWriteLocation();
dictionaryFile.seek(ptr); // crashes if ptr is negative
My question is how to solve this problem. Should I take the absolute value of the hashcode? Or will I cause problems regarding randomness of the hash (I suspect I will be halving the output space), etc, by doing so? Is there a better way?
NOTE: With hashing there is always the possibility of collisions. Thus, I'm handling collisions by jumping a fixed number of slots in the file until I find a free slot.
Upvotes: 1
Views: 1866
Reputation: 140613
A hash isn't random. Over-simplified, it is nothing but a numeric value computed "over" some data ( see here for example ).
In that sense: by using Math.abs()
you are first of all increasing the likelihood of collisions.
In other words: your whole idea sounds like the wrong approach. Because depending on the number of strings to store, and that FILESIZE constant, you sooner or later (inevitably!) will encounter two different strings being put in the same spot.
Thus: if your requirement is to always store different strings in different slots then hashing can't work for you. If that requirement is not important for you, then sure, Math.abs()
"fixes" your exception.
Upvotes: 3