Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

If two objects have same hashcode then they may or may not be equal

Hi,

I am reading as below

If two objects have same hashcode then they may or may not be equal


can you please provide simiple example to understand above
Avatar of dpearson
dpearson

HashCode in Java is an integer:

public int hashCode()

So a really simple example of how 2 values can have the same hash code but not be equal, is if you hash a Long:

int myHashCode = new Long(25).hashCode() ;

Since there are a *lot* less integers than there are longs:

Integer.MAX_VALUE =  2147483647
Integer.MIN_VALUE = -2147483648

Long.MAX_VALUE =  9223372036854775807
Long.MIN_VALUE = -9223372036854775808

it follows that a lot of the longs must hash to the same hashCode as many other longs.
On average each long value will collide with (generate the same hashcode) as about 2147483647 other longs, even though each long is  a unique value (and so not equal).

Make sense?

Doug
SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
To understand it in better terms, assume that

1) You have 10 buckets numbered from 0 to 9.

2) You are using mod of 10  for generating hash

4) Take two number 9 and 19 both will come under same hash : 9

Now hash is same but numbers are not same
Avatar of gudii9

ASKER


public class Test {

      /**
       * @param args
       */
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            System.out.println(new Integer(1).hashCode());
            System.out.println(new Long(1).hashCode());
            //System.out.println((new Integer(1).hashCode()).equals(new Long(1).hashCode()));

      }

}

above gave below output.
1
1


i wonder why they have same hashCode even though different types. Is it is bug in java?
Avatar of gudii9

ASKER

2) You are using mod of 10  for generating hash

in real time what mod we use to generate hash?
please advise
i wonder why they have same hashCode even though different types. Is it is bug in java?
No - what makes you think that?

in real time what mod we use to generate hash?

You mean in real life? The best way to find that out is to look at the source code
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial