evgenii ershenko - 1 year ago 96
Java Question

Java Faster Equals method For float type

As I know set.add use equals method of FastFloat

For me important only first two digits after point(!!!), so in the equals method to make equals faster I use

`Math.abs() >= 0.001`
but I don't understand why this code return
`2`
`1`
because
`Math.abs(3.54 - 3.5405) < 0.001`

Code:

``````import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class st {

public class FastFloat {
private float ff;

public FastFloat(float ff) {
super();
this.ff = ff;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + Float.floatToIntBits(ff);
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof FastFloat))
return false;
FastFloat other = (FastFloat) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
/*          if (Float.floatToIntBits(ff) != Float.floatToIntBits(other.ff))
return false;*/
if (Math.abs(ff - other.ff) >= 0.001)
return false;
return true;
}

private st getOuterType() {
return st.this;
}

}
public static void main(String[] args) {
List<Set<FastFloat>> lsff = new ArrayList<>();
Set<FastFloat> sff = lsff.get(0);
st x = new st();
System.out.println(lsff.get(0).size());
}

}
``````

Your `hashCode()` method gives different results for `ff==3.54` and `ff==3.5405`, so they are assigned to different buckets of the `HashSet` and your `equals` method is never used to test if they are equal.
If `a.equals(b)`, `a.hashCode()` must be equal to `b.hashCode()`. That's the contract.
From the `equals()` Javadoc :