File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes equals and hashCode?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equals and hashCode??" Watch "equals and hashCode??" New topic
Author

equals and hashCode??

Rishi Wright
Ranch Hand

Joined: Jun 25, 2003
Posts: 46
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

Joined: May 05, 2000
Posts: 13974
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.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Andres Gonzalez
Ranch Hand

Joined: Nov 27, 2001
Posts: 1561
Rishi, as Thomas said, the compiler will not complain. It is your responsability to follow the contract so you can get accurate results.


I'm not going to be a Rock Star. I'm going to be a LEGEND! --Freddie Mercury
 
wood burning stoves
 
subject: equals and hashCode??