i have a class whose equality is based on 2 fields such that if either one is equal then the objects of this type are considered equal. how can i write a hashCode() function for
EDIT: I didn't read the question carefully.
--
I'll use commons-lang jar.
XOR the members hashCode should works. As they should implements hashCode() and equals() correctly.
However, your code may wrong if you don't protect your hashCode. Once it was hashed, it should not be changed. It should be prevented from being happen.
public hashCode(){
return new AssertionError();
}
or
public class MyClass {
final int id;
final String name;
// constructor
}
or
public class MyClass {
private int id;
private String name;
boolean hashed=false;
public void setId(int value){
if(hashed)throw new IllegalStateException();
this.id=value;
}
public void setName(String value){
if(hashed)throw new IllegalStateException();
this.name=value;
}
// your equals() here
public hashCode(){
hashed=true;
return new HashCodeBuilder().append(id).append(name).toHashCode();
}
}