Is Float.equals (almost) completely useless and what should I use instead?

Given that:

It would seem that Float.equals in its current form are almost completely useless.

Am I missing something, or are there times when it is advisable to use Float.equals, except in the extremely rare case that you want to check for binary equality?

And if so, is it really done to overturn its own identikit epsilon function (as recommended in the first link), or is there an existing shell for this amazingly generic operation?

Also, does Double / Float.compare have the same problem, or is there an existing comparator that accepts epsilon?

(Note that I cannot change existing libraries from Floats to BigD)

+7
java
source share
1 answer

Float.equals useless if you are comparing Floats yourself, but it also checks the type of argument and reflexive. Do not forget that equals automatically called in collections, for example.

Here is the source code:

 public boolean equals(Object obj) { return (obj instanceof Float) && (floatToIntBits(((Float)obj).value) == floatToIntBits(value)); } 

This allows any instance of Float , including new Float("NaN") , to be equal to itself, which is part of the general equal contract and new Float("-0") be different from new Float("0") , which can be useful ( and consistent with hashCode ).

Regarding the second part: there are not many cases when you are dealing with real problems, when your epsilon is not related to any context or physical dimension (or you probably should not use Float , but BigDecimal ). Semantically, equality of floating point numbers does not really make sense. At best, you are interested in distances.

+3
source share

All Articles