java comparator, how to sort by integer?

后端 未结 6 995
一整个雨季
一整个雨季 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:21

    Just replace:

    return d.age - d1.age;
    

    By:

    return ((Integer)d.age).compareTo(d1.age);
    

    Or invert to reverse the list:

    return ((Integer)d1.age).compareTo(d.age);
    

    EDIT:

    Fixed the "memory problem".
    Indeed, the better solution is change the age field in the Dog class to Integer, because there many benefits, like the null possibility...

提交回复
热议问题