Difference between Comparable and Comparator?

后端 未结 3 1417
忘了有多久
忘了有多久 2021-01-21 04:07

My understand is Comparator can compare multiple objects from different classes while Comparable can only compare one onject with another instance in the same class.

C

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-21 04:17

    I think that when we want compare a user defined class by multiple attribute naturally ,is better that we use from Comparator interface that permitted us create some classes that implemented comparator interface and compare each one of attributes.in this case we have a below code :

    public class Student{
    private String name;
    private String ranking;
    private int age;
    private String country;
    
    // getter and setter
    }
    
    public class NameComparator implements Comparator{
    //compare by name attribute
    }
    public class AgeComparator implements Comparator{
    //compare by Age attribute
    }
    public class CountryComparator implements Comparator{
    //compare by Country attribute
    }
    public class RankingComparator implements Comparator{
    //compare by Ranking attribute
    }
    

    But when we want compare a user defined class by using just one attribute There is no need to comparator , instead of it we can use comparable interface as below code:

    public class Student{
    private String name;
    private String ranking;
    private int age;
    private String country;
    
    // getter and setter
    
    public int CompareTo(Object obj1){
    //implement comparation by name or age or etc
    }
    }
    

    And one of the place that is good , if we used from Comparator interface is for built in classes that have implemented CompareTo method such as number and etc.

提交回复
热议问题