Posted July 13, 20205 yr Heyy, in every recent version of Forge I've looked at, the #hashCode() method for BlockPos is overwritten in Vec3i as follows: public int hashCode() { return (this.getY() + this.getZ() * 31) * 31 + this.getX(); } (Credit to Mojang or the Forge Team) This would result in duplicate hashes for many positions. Technically there are only 31k positions which this could represent. Positions like (31 | 0 | 0) and (0 | 1 | 0) have the same hash code. Is this something that is just overlooked in mods today or is there a safe implementation for hashing BlockPos's? Let's say for example I have some type of structure that is 32 x 32 x 32 blocks big and I want to store something in a HashMap as in HashMap<BlockPos, Block>. This would lead to errors because of the duplicate hash I mentioned above.
July 13, 20205 yr I believe that the last time I looked into doing something similar, I decided to make my HashMaps per-chunk to prevent this issue.
July 13, 20205 yr not sure if this is related but in BlockSnapshot @Override public int hashCode() { int hash = 7; hash = 73 * hash + this.getMeta(); hash = 73 * hash + this.getDimId(); hash = 73 * hash + this.getPos().hashCode(); hash = 73 * hash + this.getRegistryName().hashCode(); hash = 73 * hash + Objects.hashCode(this.getNbt()); return hash; } maybe it is not used directly? Edited July 13, 20205 yr by poopoodice
July 13, 20205 yr Hash codes are explicitly NOT guaranteed unique. that's why equals exists and is tied to hashCode. think about it, how would you shove 96 bits of information (3 ints) into 32 bits (1 int) hash code uniquely? literally impossible. The standard practice is to try and spread out the hash codes when you can to spread out the collisions. Which is typically implemented by multiplying intermediate hash codes by some prime number. In this case 31. And no there is not 31k possible values for a vec3i hash code. there are 2^32 possibilities. I do Forge for free, however the servers to run it arn't free, so anything is appreciated. Consider supporting the team on Patreon
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.