Why is the maximum capacity of a Java HashMap 1<<30 and not 1<<31?

tesnik03 picture tesnik03 · Feb 7, 2014 · Viewed 13.1k times · Source

Why is the maximum capacity of a Java HashMap 1<<30 and not 1<<31, even though the max value of an int is 231-1? The maximum capacity is initialized as static final int MAXIMUM_CAPACITY = 1 << 30;

Answer

initramfs picture initramfs · Feb 7, 2014

Java uses signed integers which means the first bit is used to store the sign of the number (positive/negative).

A four byte integer has 32 bits in which the numerical portion may only span 31 bits due to the signing bit. This limits the range of the number to 2^31 - 1 (due to inclusion of 0) to - (2^31).