Your question is a bit vague, but if the only goal is to have different sorting algorithms depending on which property you would like to use, rather use Comparator .
public class Person { private String name; private int age; public static Comparator COMPARE_BY_NAME = new Comparator<Person>() { public int compare(Person one, Person other) { return one.name.compareTo(other.name); } } public static Comparator COMPARE_BY_AGE = new Comparator<Person>() { public int compare(Person one, Person other) { return one.age > other.age ? 1 : one.age < other.age ? -1 : 0;
which you can use as follows:
List<Person> persons = createItSomehow(); Collections.sort(persons, Person.COMPARE_BY_NAME); System.out.println(persons); // Ordered by name. Collections.sort(persons, Person.COMPARE_BY_AGE); System.out.println(persons); // Ordered by age.
Regarding the actual implementation of equals() , I would prefer it to return true when both Person objects are technically or naturally identical. For comparison with technical identity, you can use a PK created using DB:
public class Person { private Long id; public boolean equals(Object object) { return (object instanceof Person) && (id != null) ? id.equals(((Person) object).id) : (object == this); } }
or just compare each property for comparison on a natural identity:
public class Person { private String name; private int age; public boolean equals(Object object) { // Basic checks. if (object == this) return true; if (object == null || getClass() != object.getClass()) return false; // Property checks. Person other = (Person) object; if (name == null ? other.name != null : !name.equals(other.name)) return false; if (age != other.age) return false; // All passed. return true; } }
Remember to override hashCode() when you override equals() .
See also:
source share