Description
Description:
The documentation on this page currently presents the following code example for a Comparator<Integer>
in the Dealing with Null Values
section. In this section, the author states:
Suppose you need to write a null-safe comparator of integers to sort a list of integers. The convention you decide to follow is to push all the null values at the end of your list, meaning that a null value is greater than any other non-null value. And then you want to sort non-null values in their natural order.
To illustrate this behavior, the documentation provides the following code example:
Comparator<Integer> comparator = (i1, i2) -> {
if (i1 == null && i1 != null) { // <-- This condition can never be true! [NOTE]
return 1;
} else if (i1 != null && i2 == null) {
return -1;
} else {
return Integer.compare(i1, i2);
}
};
Problem:
The condition i1 == null && i1 != null
in line 3
is logically impossible and will always evaluate to false
because i1 cannot be both null
and not null
at the same time. This block will never execute. This may confuse readers and does not demonstrate correct null handling.
Suggested Correction:
Update the example to properly handle nulls. For example:
Comparator<Integer> comparator = (i1, i2) -> {
if (i1 == null && i2 != null) {
return 1;
} else if (i1 != null && i2 == null) {
return -1;
} else if (i1 == null && i2 == null) {
return 0;
} else {
return Integer.compare(i1, i2);
}
};
Request:
Please update the documentation to use a correct null check example for clarity and accuracy.