I found the following code, which sorts the personList
array by the Person
's age in descending order.
personList.sort((Person p1, Person p2) -> p2.getAge() - p1.getAge());
However, I'm having trouble understanding how it works. It seems that the sort()
function subtracts p1
and p2
's age but I don't get how that allows the function to return the sorted array.
How does sort()
iterate over the array and uses the comparator for every object in that array?