So I'm trying to do a simple program that can find the module of a Complex Number using generics and compares two modules:
public class ComplexNumber <T extends Number,U extends Number>
implements Comparable<ComplexNumber<T, U>>
{
private T real;
private U imaginary;
public ComplexNumber(T real, U imaginary)
{
this.real=real;
this.imaginary=imaginary;
}
public T getReal()
{
return real;
}
public int compareTo(ComplexNumber<?, ?> o)
{
return this.modul().compareTo(o.modul());
}
public U getImaginary()
{
return imaginary;
}
public double modul()
{
double c=Math.sqrt(real.doubleValue()*real.doubleValue()+imaginary.doubleValue()*imaginary.doubleValue());
return c;
}
public String toString()
{
return String.format("%.2f+%.2fi", real.doubleValue(), imaginary.doubleValue());
}
}
However it gives me two real time errors one in the .compareTo function stating:"Cannot invoke compareTo(double) on the primitive type double"
and one in the beginning of the class: "Multiple markers at this line - The type ComplexNumber must implement the inherited abstract method Comparable>.compareTo(ComplexNumber) - The type ComplexNumber must implement the inherited abstract method "
you're looking for something along the lines of:
@Override
public int compareTo(ComplexNumber<T, U> o) {
// logic
}
edit
if you definitely need to use wildcards then you'll need to change the class declaration to:
class ComplexNumber <T extends Number,U extends Number> implements Comparable<ComplexNumber<?, ?>>
in which case you can leave the compareTo
method signature as is.
regarding the first error you've received, this is because you're trying to call the compareTo
method on a primitive type double
which would not work at all. To solve the problem, you'd want to use Double.compare
and pass in the appropriate data.
@Override
public int compareTo(ComplexNumber<?, ?> o) {
return Double.compare(modul(), o.modul());
}