I have array of objects person (int age; String name;)
.
How can I sort this array alphabetically by name and then by age?
Which algorithm would
Have your person class implement Comparable
and then implement the compareTo method, for instance:
public int compareTo(Person o) {
int result = name.compareToIgnoreCase(o.name);
if(result==0) {
return Integer.valueOf(age).compareTo(o.age);
}
else {
return result;
}
}
That will sort first by name (case insensitively) and then by age. You can then run Arrays.sort()
or Collections.sort()
on the collection or array of Person objects.