How to use float effectively in equals ()?

I have the following immutable HSL class that I use to represent color and the RGBA color calculation helper with a bit more refinement.

public class HSL {
  protected final float hue;
  protected final float saturation;
  protected final float lightness;

  public HSL(float hue, float saturation, float lightness) {
    this.hue = hue;
    this.saturation = saturation;
    this.lightness = lightness;
  }

  // [snip] Removed some calculation helper functions

  @Override
  public String toString() {
    return "HSL(" + hue + ", " + saturation + ", " + lightness + ")";
  }

  @Override
  public int hashCode() {
    return
        37 * Float.floatToIntBits(hue) +
        37 * Float.floatToIntBits(saturation) +
        37 * Float.floatToIntBits(lightness);
  }

  @Override
  public boolean equals(Object o) {
    if (o == null || !(o instanceof HSL)) {
      return false;
    }

    HSL hsl = (HSL)o;
    // We're only worried about 4 decimal places of accuracy. That more than the 24b RGB space can represent anyway.
    return
        Math.abs(this.hue - hsl.hue) < 0.0001f &&
        Math.abs(this.lightness - hsl.lightness) < 0.0001f &&
        Math.abs(this.saturation - hsl.saturation) < 0.0001f;
  }
}

HashMap , RGBA, int , float . epsilon , , float, , , Float.floatToIntBits. ? , ?

+4
5

, . , , .

( 4), float 10 000 long. - .

, . , , Javadocs , float .

+4

equals() . equals(). hashCode(), , API . , HashSet, , , , remove(). .

+1

, hashCode(), equals().

, "" hashCode(), , , .

, , - , , , hashCode - .

+1

hashcode , . , , equals().

, equal (.. hashcode() ), .

0

I think you could try to weaken the implementation hashCodein order to prevent it from breaking the contract with equals- I mean, if it equalsreturns true, then it hashCodereturns the same value, but not necessarily another one around.

0
source

Source: https://habr.com/ru/post/1535505/


All Articles