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
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...