aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Reg Hashcodes 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 "Reg Hashcodes" Watch "Reg Hashcodes" New topic
Author

Reg Hashcodes

Vishnu Munnangi
Ranch Hand

Joined: Sep 28, 2004
Posts: 114
Hi everybody,

I wanted to compare to objects for equality, and get the hashcode of the objects. I have overridden equals method so that the objects which contain the same data will return true. I read in some book that whenever you override the equals method, you should also override the hashCode method. Can anyone explanin me how to override the hashCode method so that the hashCode values of the objects be equal.

The code is as follows:

public class Equals {
int i;
public Equals(int i){
this.i = i;
}
public boolean equals(Equals obj){
if(obj.i == i)
return true;
else
return false;
}
public int hashCode(){
//Code to write here. so that the two objects which are equal give same hashcode value
}
public static void main(String args[]){
Equals obj1 = new Equals(1);
Equals obj2 = new Equals(1);
System.out.println(obj1.equals(obj2));
}
}

Thanks in Advance.
Saheed Adepoju
Ranch Hand

Joined: Jun 23, 2004
Posts: 267
Hi
Well from what u have written if u want it to return the same hashcode u could simply put return 0; which will ensure that the same number would be returned whenever u call it. There are other techniques though but i guess this would solve ur problem. Cheers.
Saheed.
SCJP 1.4(Coming soon..)
Imagination is better than Knowledge.


Saheed Adepoju<br />SCJP 1.4<br />SCJD (B&S..In progress)
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
This should answer your question.


SCJP Tipline, etc.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reg Hashcodes