Junior — Middle
In what cases and what specific values does the Comparator interface return when performing a comparison?
sobes.tech AI
Answer from AI
The Comparator interface in Java is used for comparing two objects. The method compare(T o1, T o2) returns:
- A negative number if o1 is less than o2.
- Zero if o1 is equal to o2.
- A positive number if o1 is greater than o2.
This allows determining the order of objects during sorting or other comparison operations.
Example:
Comparator<Integer> comparator = (a, b) -> a - b;
int result = comparator.compare(5, 10); // result will be negative