i dont understand what is 0x7fffffff mean. is there any other way to code getHashValue method?

public int getHashValue(K key){
    return (key.hashCode() & 0x7fffffff) % size;

i dont understand what is 0x7fffffff mean. is there any other way to code getHasValue method?

asked on Stack Overflow Mar 31, 2018 by b.alex • edited Nov 30, 2019 by Marco R.

3 Answers


The constant 0x7FFFFFFF is a 32-bit integer in hexadecimal with all but the highest bit set.

Despite the name, this method isn't getting the hashCode, rather looking for which bucket the key should appear in for a hash set or map.

When you use % on negative value, you get a negative value. There are no negative buckets so to avoid this you can remove the sign bit (the highest bit) and one way of doing this is to use a mask e.g. x & 0x7FFFFFFF which keeps all the bits except the top one. Another way to do this is to shift the output x >>> 1 however this is slower.

A slightly better approach is to use "take the modulus and apply Math.abs". This uses all the bits of the hashCode which might be better.


public int getBucket(K key) {
    return Math.abs(key.hashCode() % size);

Even this is not ideal as some hashCode() have a poor distribution resulting in a higher collision rate. You might want to agitate the hashcode before the modulus etc.

public int getBucket(K key) {
    return Math.abs(hash(key) % size);

HashMap in java 8 uses this

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);

The function is simple as it handles collisions efficiently. In Java 7 it used this function.

static int hash(int h) {
    // This function ensures that hashCodes that differ only by
    // constant multiples at each bit position have a bounded
    // number of collisions (approximately 8 at default load factor).
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
answered on Stack Overflow Apr 1, 2018 by Peter Lawrey • edited Oct 25, 2018 by Krishna Pandey

That's the Hexadecimal representation of the Max. Integer

You can check here

answered on Stack Overflow Mar 31, 2018 by mooga

0x7fffffff just remove the signal getting the complement of the number.

Using Java REPL you can see the results of the operation

> -7 & 0x7fffffff
java.lang.Integer res1 = 2147483641
> 2147483641 & 0x7fffffff
java.lang.Integer res2 = 2147483641
> 2147483641 + 6
java.lang.Integer res3 = 2147483647
> 7 + 2147483641
java.lang.Integer res4 = -2147483648

In the binary representation, the first bit is the signal. If you set it to zero you will get positive complementary if the number is negative. Or the same number if positive.

answered on Stack Overflow Apr 4, 2018 by Victor

User contributions licensed under CC BY-SA 3.0