0

I already know how to compare floats and this is not the question.

When I compare float I cannot just do that:

if(flot1 == flot2) {
    // do something
}

Indeed I was always taught to do something like this:

if(Math.abs(float1 - float2) < epsilon) {
    // do something
}

But the question is when I use float wrappers... for example there is something as simple as the method equal():

if(floatWrapper1.equals(floatWrapper2)) {
    // do something
}

But reading the documentation that this is equivalent to:

if(floatWrapper1.floatValue() == floatWrapper2.floatValue()) {
    // do something
}

That is the same like the example (2) that is wrong for the purpose of comparison.

Looking in internet I then found some examples like this:

if(Float.compare(flotWrapper1, floatWrapper2) == 0) {
    // do something
}

But, I was wonder if this is right neither. How should I then compare two float wrappers?

user1883212
  • 7,539
  • 11
  • 46
  • 82
  • 3
    You can also use `if(Math.abs(float1 - float2) < epsilon)` with Floats... – assylias Sep 21 '15 at 16:58
  • 1
    possible duplicate of [What's wrong with using == to compare floats in Java?](http://stackoverflow.com/questions/1088216/whats-wrong-with-using-to-compare-floats-in-java) – Federico Piazza Sep 21 '15 at 17:01
  • 1
    @Bubletan not exactly: the op seems to assume that it will only work with primitives - I added a comment to say that it would also work with the boxed type. – assylias Sep 21 '15 at 17:02
  • @assylias Oh yeah, nevermind. – Bubletan Sep 21 '15 at 17:03

1 Answers1

2

The simple answer is because of Auto boxing, comparing Floats is no different than comparing floats. Save for a null pointer check, you can treat them equivalently.

Will Hartung
  • 115,893
  • 19
  • 128
  • 203