Comparable difference comparator and compartor and understanding

Overview: both comparator for comparing the same type commonly employed to achieve the sort function.
 
Comparable achieve :( internal sorting, implemented in the pojo)

 
Comparator achieve :( external sort, pojo not implemented)
public static void compareTest(){
    List<User> list = new ArrayList<User>();
    list.add(new User("bob",27));
    list.add(new User("club",26));
    Collections.sort(list, new Comparator<User>() {
        public int compare(User o1, User o2) {
            return o1.getAge()-o2.getAge();
        }
    });
    //[User{name='club', age=26}, User{name='bob', age=27}]
    System.out.println(list.toString());
}

the difference:
Comparable:  may be implemented in a corresponding compareTo method pojo class, then call
Collections.sort or arrays.sort will automatically call the way you achieve. But only one sort.

Comparator: you can achieve a variety of different sort, just the way you want to sort of take as a parameter to sort.
I can sort can be sorted by name, by age such as the above code only. See specific code to achieve the above
 
But both results were consistent return: this person - who <- before moving the image to achieve a positive sequence

 

Guess you like

Origin www.cnblogs.com/lanSeGeDiao/p/10931441.html