Search code examples
javaclassequals

How do I define an equals function for a custom complex numbers class in Java?


Here's a piece of code from my complex numbers class:

public class complex {
    private double re;
    private double im;

    public complex(double real, double imag) {
        re = real;
        im = imag;
    }

    public Boolean equals(complex b) {
        complex a = this;
        return a.re==b.re && a.im==b.im;
    }

    public Boolean equals(double alpha){
        complex a = this;
        return a.re==alpha && a.im==0;
    }
    ...
}

And here's what I'm trying to use it for:

public class cubic_cardano {
    public static void solveCubic(complex a, complex b, complex c, complex d){
        if (a==b && b==c && c==d && d==0) {
            ...
        }
    }
    ...
}

Comparing a complex number to a complex number works just fine while comparing a complex number to a double gives an error:

Incompatible operand types complex and int

What could be the reason and how can I make it work?


Solution

  • You cannot use equals or == to compare two objects with unrelated types. Instead you should compare to a Complex with value zero:

        public static void solveCubic(Complex a, Complex b, Complex c, Complex d){
            if (a.equals(b) && b.equals(c) && c.equals(d) && d.equals(new Complex(0, 0))) {
                //...
            }
        }
    

    p.s. there are several other issues with your Complex class, as others have noted in the comments. Here is the version I am using:

    import java.util.Objects;
    
    public class Complex {
        private double re;
        private double im;
    
        public Complex(double real, double imag) {
            re = real;
            im = imag;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Complex other = (Complex) o;
            return re == other.re && im == other.im;
        }
    
        @Override
        public int hashCode() {
            return Objects.hash(re, im);
        }
    }