Quick example is a collection of users' first and last name.

One method requires that I compare using the first name, another using the last name. Is it possible to have two different compareTo()?

Or am I just better off creating two different value classes?

有帮助吗?

解决方案 2

Using compareTo means that you are using the Comparable interface, which defines only one "natural order" for your class.

To have any other ordering, it's best to create a separate class that implements Comparator for each ordering you need. You don't need to create a different value class.

其他提示

You can use the Comparator in java

In this example I m comparing the Fruit objects on the basis of fruitName using Comparable CompareTo method and quantity here by using Comparator ,if you want this object to be compare using fruitDesc then create one more static innerclass as I did for fruitName

public class Fruit implements Comparable<Fruit>{

    private String fruitName;
    private String fruitDesc;
    private int quantity;

    public Fruit(String fruitName, String fruitDesc, int quantity) {
        super();
        this.fruitName = fruitName;
        this.fruitDesc = fruitDesc;
        this.quantity = quantity;
    }

    public String getFruitName() {
        return fruitName;
    }
    public void setFruitName(String fruitName) {
        this.fruitName = fruitName;
    }
    public String getFruitDesc() {
        return fruitDesc;
    }
    public void setFruitDesc(String fruitDesc) {
        this.fruitDesc = fruitDesc;
    }
    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public int compareTo(Fruit compareFruit) {

        int compareQuantity = ((Fruit) compareFruit).getQuantity(); 

        //ascending order
        return this.quantity - compareQuantity;

        //descending order
        //return compareQuantity - this.quantity;

    }

    public static Comparator<Fruit> FruitNameComparator 
                          = new Comparator<Fruit>() {

        public int compare(Fruit fruit1, Fruit fruit2) {

          String fruitName1 = fruit1.getFruitName().toUpperCase();
          String fruitName2 = fruit2.getFruitName().toUpperCase();

          //ascending order
          return fruitName1.compareTo(fruitName2);

          //descending order
          //return fruitName2.compareTo(fruitName1);
        }

    };
}

No you cannot, but you can create a separate Comparator for each ordering.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top