Solve Comparator does not return 0 for equal elements

Viewed 893

Useful information:

IDE: IntelliJ JDK: 8u271

I have a warning which I do not understand nor do I know how to solve it. Warning:

Comparator does not return 0 for equal elements

The warning highlights

(a, b)

within this line of code.

private final Comparator<Entity> renderSorter = (a, b) -> {
    if (a.getY() + a.getHeight() < b.getY() + b.getHeight())
        return -1;
    return 1;
};

What is the meaning of the warning and how do I solve it?

2 Answers

You have to add a case to check if two values are equal the comparator should return 0. Right now it will return -1 or 1.

private final Comparator<Entity> renderSorter = (a, b) -> {
    return Integer.compare(a.getY() + a.getHeight(), b.getY() + b.getHeight()); 
};

This will do the trick for you. Delegate the responsibility of comparision to the Integer class compare method.

The contract of the Comparator interface says:

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

That warning is telling you that you Comparator never returns zero, which I assume you can see from examining your code.

You can solve the warning by making your Comparator return zero when the two Entity objects are equal, in the sense of the Comparator, not actually checking the two objects for equality.

Related