Domanda

I'm playing around with the Comparisonchain using this example. But it just shows one way to sort these objects.

  public class Fruit implements Comparable<Fruit> {
  private String name;
  private String family;
  private int calories;

  @Override
  public int compareTo( Fruit otherFruit ) {
    return ComparisonChain.start()
      .compare( name, otherFruit.name )
      .compare( family, otherFruit.family )
      .compare( calories, otherFruit.calories )
      .result();
  }
}

I was wondering now if it is possible to sort based on the needs of the end user. How would I have to implement it, if the sorting criteria are not fixed? E.g. Someone wants to sort first by name, then by calories and that's it. The next one wants to sort by familiy, then by calories and then by name. and so on. People might also want to sort descending instead of ascending.

Can anybody give me some hints on how to solve it?

È stato utile?

Soluzione

A Comparable should implement exactly one way of comparing. Allowing it to be changed actually breaks the contract of Comparable, which requires that (to quote the Javadoc) sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. If you can change the comparison that individual Fruit objects use, you can have an object x that says it's greater than y, while y says it's greater than x, and so on. Imagine if you have a List<Fruit> containing objects that are each configured to use a different sort order... trying to sort that list would just be chaos and not produce anything useful.

If you want multiple alternative ways of sorting, create Comparators implementing each of those ways and expose them to users in some way. Then a single Comparator can be passed to the sort method (or TreeSet constructor, or whatever), ensuring that all comparisons use that logic.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top