I have a POJO say Animal.java which looks as under:
class Animal{
String name;
String owner;
String color;
}
Two animals are equal if they have same name and ownwer. So, I need to override equals and hashcode accordingly:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + name.hashCode();
result = prime * result + owner.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Animal other = (Animal) obj;
if (!name.equals(other.name))
return false;
if (!owner.equals(other.owner))
return false;
return true;
}
Now the problem is that whenever I display an ArrayList on Animal , I want to display it sorted based on color
field.
If I use Comparable and override compareTo as follows:
@Override
public int compareTo(Animal o) {
return color.compareTo(o.color);
}
Then my equals and compareTo methods are inconsistent. This is also a problem.
So, how do i sort my ArrayList of Animal
based on Animal.color
?