I want to override “public boolean equals(Object obj)” function, for name and age, in my class named MyObject whose structure is given below
public class MyObject{
private String name;
private int age;
}
How can i ?
@balusC :
What about this ?
vo = new MyObject() {
public boolean equals(Object obj) {
return ((MyObject)obj).name().equals(this.getName());
}
vo = new MyObject() {
public boolean equals(Object obj) {
return ((MyObject)obj).age() == (this.getAge());
Your question is a bit vague, but if the sole purpose is to have different sorting algorithms depending on what property you’d like to use, then rather use a
Comparator.which you can use as follows:
As to the actual
equals()implementation, I’d rather let it return true when the bothPersonobjects are techically or naturally identical. You can use either a DB-generated PK for this to compare on technical identity:or just compare every property to compare on natural identity:
Don’t forget to override
hashCode()as well when you overrideequals().See also:
equals()andhashCode()