I have some items which have an id and a value and I am looking for the maximum element.
The values are floats/doubles and as tie breaking I want to use the object with the smaller id.
One approach is the following:
double maxValue = Double.NEGATIVE_INFINITY;
Item maxItem = null;
for (Item item : items) {
if (item.value() > maxValue) {
maxValue = item.value();
maxItem = item;
} else if (item.value() == maxValue && item.id() < maxItem.id()) {
maxItem = item;
}
}
However, this includes an quality-comparison using floating point numbers, which is discouraged and in my case also creates a critical issue in the code analysis step.
Of course, I can write something to avoid the issue, e.g. use >=
for the second comparison, however from the point of readability my future me or any other reader might wonder if it is a bug.
My question: Is there an approach which expresses well the intent and also avoids float comparison using ==
for this task?