Here is an example where the comparator is not defined on the line.
In any case, this is acceptable, but I think this method is easier to understand.
class Person { int id; public getId(){ return this.id; } } class PersonComparator implements Comparator<Person> { @Override public int compareTo(Person personOne, Person personTwo) { reuturn personOne.getId() - personTwo.getId(); } }
Using:
Person[] personArray = buildArraySomehow(); PersonComparator pc = new PersonComparator(); Arrays.sort(personArray, pc);
A comparator is an interface with only one method: compareTo.
When you create a Comparator, this is the only method you need to implement.
Note that PersonComparator.compareTo () returns nothing, but returns the difference between the identifiers of two Person objects.
This is due to how the compareTo () method should work:
- If the first element is "preceded" by the second element, a negative number is returned.
- If the first element "comes after" the second paragraph, a positive number must be returend.
- If two elements are equivalent (in terms of ordering), zero should be returned.
Check out the documentation for Comparator for more information ...
source share