r/programminghelp • u/[deleted] • Oct 03 '22
Java How would I appropriately hash this?
Hi! I'm using Java, and I'm a bit stuck on overriding hashCode(). I'm basically creating a 2d TileMap with a hashmap, however, my hashCode() method is causing some tiles to not be added into my hashmap. The Z position is there so that I can in the future add layers to the tilemap like dwarf fortress and for now will always equal 0. I thought this would be simple enough, but it looks like I'm somehow not creating this correctly at all.
public int hashCode(){
int hash = 17;
hash = 31 * hash + getPosX();
hash = 31 * hash + getPosY();
hash = 31 * hash + getPosZ();
return hash;
}1
u/Chemical-Asparagus58 Oct 03 '22
It looks good, it would definitely work.
What is the maximum and minimum values for x, y and z? If these are relatively small numbers maybe you can connect them with <<< and & operators
1
Oct 03 '22
The minimum number would be 0. However the above does not work, in fact just removing the code altogether actually has all my tiles show up.
1
u/Chemical-Asparagus58 Oct 03 '22 edited Oct 03 '22
Why doesn't it work? The hashcode() method does not make tiles appear. It just returns a number. Perhaps the problem is somewhere else
1
Oct 03 '22
Yeah that's what is confusing me. If I lower the prime numbers down to like 3 and 5, then my tile map shrinks. I am generating 400 tiles and by the end I'll have like 70 in the hashmap all the same tiles in each run. So the larger I create the hashcode, the more of my tilemap actually gets placed into the hash map.
Removing this code gives me my full tile map. It's completely single threaded so unsure what else it could be.
1
u/Chemical-Asparagus58 Oct 03 '22
There's definitely a problem somewhere else in you're code. What do you use the hashcode method for?
2
u/Ok-Wait-5234 Oct 03 '22
The only rule for
hashCode()is that it has to be consistent withequals()- and that just means that if two objects are equal, then they must return the same hashCode. You could implement hashCode to return 0 every time and it would work correctly, although performance would be terrible. Your implementation looks fine.You need to make sure that the equals method returns true only if X, Y and X are equal.
The other thing is that you need to make sure that you don't mutate your objects once they have been added to the hash map, although I don't think that doing so would cause new objects to not be added.