• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals and hashCode??

 
Rishi Wright
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi 'LL
I have question on hashcode..here is the code
class Test {
int s;
int k;
public boolean equals(Object o){
try{
Test t=(Test)o;
return true;}
catch(ClassCastException e){
return true;}
}
public int hashCode(){
return k^s;}
public static void main(String[]args){
Test t=new Test();
t.s=10;
Test t1=new Test();
t1.k=6;
System.out.println(t.equals(t1));
System.out.println(t1.hashCode()==t.hashCode());

}
}
here Iam trying to override both equals(object) and hashCode().
The above code working fine printing true and false.
My question is , IS this legal to override hashcode to return different integers though according to equals method they r equal.
In java API hashcode MUST be equal if equals method return true.
so why the above code not giving any error???
Thnx
rishi
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rishi Wright:
The above code working fine printing true and false.
My question is , IS this legal to override hashcode to return different integers though according to equals method they r equal.
In java API hashcode MUST be equal if equals method return true.
so why the above code not giving any error???
Thnx
rishi

It is illegal. How would you expect the compiler to know that it is illegal? It is the job of the programmer to insure that s/he follows the requirements. You have violated the contract and your class will not work properly if objects of this class are placed in a hash object.
 
Andres Gonzalez
Ranch Hand
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rishi, as Thomas said, the compiler will not complain. It is your responsability to follow the contract so you can get accurate results.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic