• Post Reply Bookmark Topic Watch Topic
  • New Topic

not clear with hashcodes  RSS feed

 
Lucky J Verma
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read about hashcode from many books & refernce but atill have confusion.

this i1 & i are 2 different objects but equals() still returns true .
Same thing if do using 2 Objects of same state var ,it shows unequality.

Integer i=new Integer(1);
Integer i1=new Integer(1);
System.out.println("equality "+i.equals(i1));
System.out.println("hashcode "+i.hashCode()+i1.hashCode());
Please explain me how its showing this output.

[ June 26, 2007: Message edited by: Lucky J Verma ]
[ June 26, 2007: Message edited by: Lucky J Verma ]
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I run the code, the hashCodes are the same (1). What version of Java are you using.

Any objects that are .equal() should have the same hashCode; you will run into odd problems using collections if they aren't
 
Lucky J Verma
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh ,i am really sorry i did a typo ..hashcodes are same .But my equals() withInteger sould not be true.i am not really clear. or why it should be true.I am not very clear about it .As for other objects it gives false ,even if state is same.
i will correct my posts .

Thnx
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
java.lang.Integer overrides equals() and hashCode() so that all Integer objects with the same int value are equal, and all have the same hashCode(). That's exactly what you're supposed to do when you override equals() and hashCode().

If equals() never returned true for two different objects, then it wouldn't be necessary -- you could just always use ==. Right?
 
Lucky J Verma
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes,now i got it .
Thanks a lot :-)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!