How does this @Override for Arrays.sort work in Java?
The arrow notation is a lambda function, short-hand for the same Comparator implementation. That's why you see the same results. It is not about @Override
here, what you're asking for is how a Comparator works really.
A comparator orders 2 objects in the following order:
- negative, sorts descending
- zero, does nothing
- pozitive, sorts ascending
So for the priority queue part, when the comparator sorts 1, 4, 6, 3, it compares the elements of the array and it swaps them if the difference is negative, e.g. it would swap 1 and 4, 4 and 6, etc.
For the first part of the question, you're using this implementation:
(n2[0] == n1[0])? n1[1] - n2[1]: n2[0] - n1[0]
For 2-sized integer arrays, you're comparing the arrays as following.
- If the first element of each array are not equal, you're trying to sort in descending order(i.e. bringing a [7, 0] ahead of a [4, 4])
- If the first element of each array is equal, you're trying to sort in ascending order(i.e. bringing [7,0] ahead of [7,1]).