Rotom92
Rotom92

Reputation: 766

Multiple Comparable in a class

I'd like to know if is possible implementing more Comparables for a single class. I have first to order my arraylist by a integer field and next in another part of my program i have to order it by another field. How i can do that? I thought about a custom Comparator but it didn't work.

public void OrderbyColours(ArrayList<Horses> scuOrderedByColours,
        ArrayList<Horses> ArrayScud) {
    scuOrderedByColours.addAll(ArrayScud);
    Collections.sort(scuOrderedByColours, new Comparator<Horses>() {
        public int compare(Horses o1, Horses o2) {
            return o1.Position - o2.Position;
        }
    });
}

Upvotes: 0

Views: 119

Answers (1)

Robert Mitchell
Robert Mitchell

Reputation: 892

Assuming Comparators are not working(which i'm curious as to how they're not working), or you simply don't want to use one, you could write a wrapper class that has an instance of your original class as data.

ex.

public class HorsesWrapper implements Comparable<HorsesWrapper>
{
  private Horses horses;

  public int compareTo(HorsesWrapper other)
  {
    // your sort criteria based on the Horse member.
  }
}

Upvotes: 1

Related Questions