0

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?

Manas Saxena
  • 2,171
  • 6
  • 39
  • 58
  • 2
    Don't implement `Comparable`, create a custom `Comparator` instead. Refer to the linked question. – Tunaki Aug 08 '16 at 10:29
  • Okay yes that seems correct: class AnimalNameComparator implements Comparator{ public int compare(Animal o1, Animal o2) { return o1.getColor().compareTo(o2.getColor()); } } – Manas Saxena Aug 08 '16 at 10:46

0 Answers0