java comparator, how to sort by integer?

后端 未结 6 999
一整个雨季
一整个雨季 2020-12-08 09:36

Im trying to learn comparator in java and I have found this great example online, my question is how would this code be changed so that the pet names are ordered by age and

6条回答
  •  情歌与酒
    2020-12-08 10:00

    One simple way is

    Comparator ageAscendingComp = ...;
    Comparator ageDescendingComp = Collections.reverseOrder(ageAscendingComp);
    // then call the sort method
    

    On a side note, Dog should really not implement Comparator. It means you have to do strange things like

    Collections.sort(myList, new Dog("Rex", 4));
    // ^-- why is a new dog being made? What are we even sorting by?!
    Collections.sort(myList, myList.get(0));
    // ^-- or perhaps more confusingly
    

    Rather you should make Compartors as separate classes.

    eg.

    public class DogAgeComparator implments Comparator {
        public int compareTo(Dog d1, Dog d2) {
            return d1.getAge() - d2.getAge();
        }
    }
    

    This has the added benefit that you can use the name of the class to say how the Comparator will sort the list. eg.

    Collections.sort(someDogs, new DogNameComparator());
    // now in name ascending order
    
    Collections.sort(someDogs, Collections.reverseOrder(new DogAgeComparator()));
    // now in age descending order
    

    You should also not not have Dog implement Comparable. The Comparable interface is used to denote that there is some inherent and natural way to order these objects (such as for numbers and strings). Now this is not the case for Dog objects as sometimes you may wish to sort by age and sometimes you may wish to sort by name.

提交回复
热议问题