1

My homework is to create an equal method of a class that override Object class's equal method in Java. I have coded like below but the lecturer commented that: "doubles cannot be compared for equality with ==,!= as storage is not exact." So how do I edit the code accordingly in this case? Thank you very much. class GameSettings {

private int firingInterval;
private double moveSpeed;
...
public boolean equals(Object obj) {

        //objects are equal if same firingInterval and moveSpeed
        GameSettings other;
        boolean result = false;

        //TODO

         other = (GameSettings) obj;
        if (obj instanceof GameSettings) {
            return (firingInterval == other.getFiringInterval()
                && moveSpeed == other.getMoveSpeed());
        } else {
            return result;
        }
    }
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
Fazan Cheng
  • 866
  • 1
  • 8
  • 13
  • 1
    See also http://stackoverflow.com/questions/15782529/java-double-equality and http://stackoverflow.com/questions/25160375/comparing-double-values-for-equality-in-java and http://stackoverflow.com/questions/7180952/is-checking-a-double-for-equality-ever-safe – Tunaki Sep 11 '16 at 13:10

1 Answers1

2

As your lecturer said, comparing double does not simply use equals operator. For example, you can try that 1 doesn't equal with 1.000.

Instead we often compare double by using delta between two values. If delta is relatively small so those value will equal.

public static final double EPSILON = 0.0000000001;
public boolean compare(double a, double b) {
   return Math.abs(a-b) < EPSILON;
}
hqt
  • 29,632
  • 51
  • 171
  • 250