In the below code, the hash code is always same. Why is it like that?
Code:
public class BooleanClass { public static void main(String[] args) { Boolean b1 = new Boolean(true); Boolean b2 = new Boolean(false); Boolean b3 = new Boolean(true); Boolean b4 = new Boolean(false); Boolean b5 = new Boolean(false); Boolean b6 = new Boolean(true); System.out.println(b1.hashCode()); System.out.println(b2.hashCode()); System.out.println(b3.hashCode()); System.out.println(b4.hashCode()); System.out.println(b5.hashCode()); System.out.println(b6.hashCode()); } }
Output:
1231 1237 1231 1237 1237 1231
Always the same numbers 1231
and 1237
are printed. Any reason?
The hash code itself is not guaranteed to be stable. Hash codes for identical strings can differ across versions of the . NET Framework and across platforms (such as 32-bit and 64-bit) for a single version of the . NET Framework.
Whenever two different objects have the same hash code, we call this a collision. A collision is nothing critical, it just means that there is more than one object in a single bucket, so a HashMap lookup has to look again to find the right object.
It is perfectly legal for two objects to have the same hashcode. If two objects are equal (using the equals() method) then they have the same hashcode. If two objects are not equal then they cannot have the same hashcode.
If two objects have the same hashcode then they are NOT necessarily equal. Otherwise you will have discovered the perfect hash function. But the opposite is true: if the objects are equal, then they must have the same hashcode .
The JavaDoc of Boolean.hashCode()
method says:
Returns the integer
1231
if this object representstrue
; returns the integer1237
if this object representsfalse
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With