Jump to content

Discussion: Safe to use BlockPos#hashCode() ?


Recommended Posts



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.

Link to comment
Share on other sites

not sure if this is related but in BlockSnapshot

    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 by poopoodice
Link to comment
Share on other sites

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

Link to comment
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in

Sign In Now

  • Create New...

Important Information

By using this site, you agree to our Terms of Use.