I have objects
Person{
String name;
int age;
float gradeAverage;
}
Is there an easy way to sort
Person[] ArrayOfPersons
by age?
Do I have to use Comparable or Comparator? I don't fully understand them.
I have objects
Person{
String name;
int age;
float gradeAverage;
}
Is there an easy way to sort
Person[] ArrayOfPersons
by age?
Do I have to use Comparable or Comparator? I don't fully understand them.
You can implement the Comparable interface to make your class comparable. Make sure to override the compareTo method then.
Just for completeness, when using Java 8, you can use
Comparator.comparing
to create a simple comparator for some attribute, e.g.Comparator.comparing(Person::getAge)
, or using lambda, likeComparator.comparing(p -> p.age)
, if there is not getter method for the age.This makes it particularly easy to chain comparators for different attributes, using
thenComparing
, e.g. for sorting primarily by age, and then by name in case of ties:Combine that with
Arrays.sort
, and you are done.You can check for age using a getter in your loop
However implementing Comparable is the convenient way
You can check
Comparable
documentation alsoYes just implement the
Comparable
interface.Here's an example :