Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have TWO compareTo methods for a value class?

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?

like image 814
iCodeLikeImDrunk Avatar asked Jan 22 '26 22:01

iCodeLikeImDrunk


1 Answers

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);
        }

    };
}
like image 53
Girish Avatar answered Jan 25 '26 12:01

Girish