Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Hash Code of different Boolean instances is always the same?

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?

like image 529
user3467951 Avatar asked Mar 27 '14 09:03

user3467951


People also ask

Is hashCode always the same?

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.

What is the reason for two objects getting the same hashCode?

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.

Can 2 different objects have same hashCode?

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.

Can two hash codes be equal?

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 .


1 Answers

The JavaDoc of Boolean.hashCode() method says:

Returns the integer 1231 if this object represents true; returns the integer 1237 if this object represents false.

like image 61
Gokul Nath KP Avatar answered Sep 23 '22 01:09

Gokul Nath KP