0

我必须实现一个类ComplexNumber。它有两个通用参数TU,它们必须来自某个继承自 Number 类的类。Complex 类有 2 个字段(实例变量):实部和虚部,并且必须实现这些方法:

  1. ComplexNumber(T real, U imaginary)- 构造函数
  2. getReal():T
  3. getImaginary():U
  4. modul():double- 这是复数的模
  5. compareTo(ComplexNumber<?, ?> o)- 此方法基于 2 个复数的模进行比较

除了最后一个,我已经实现了所有这些方法compareTo,因为我不知道如何使用这些通配符进行操作。

这是我的代码:这里的帮助-pastebin

class ComplexNumber <T extends Number,U extends Number> implements Comparable<ComplexNumber> {

    private T real;
    private U imaginary;

    public ComplexNumber(T real, U imaginary) {
        super();
        this.real = real;
        this.imaginary = imaginary;
    }

    public T getR() {
        return real;
    }

    public U getI() {
        return imaginary;
    }

    public double modul(){

        return Math.sqrt(Math.pow(real.doubleValue(),2)+ Math.pow(imaginary.doubleValue(), 2));

    }



    public int compareTo(ComplexNumber<?, ?> o){

        //HELP HERE 
    }




}

有人帮助这个方法吗?

4

3 回答 3

2

由于您只需要比较模数,因此您不必关心类型参数。

@Override
public int compareTo(ComplexNumber<?, ?> o) {
    return Double.valueOf(modul()).compareTo(Double.valueOf(o.modul()));
}

但是,您还必须在类型声明中添加通配符

class ComplexNumber <T extends Number,U extends Number> implements Comparable<ComplexNumber<?, ?>>
于 2013-10-29T14:37:02.940 回答
0

似乎您的两个参数都可以处理扩展 java.lang.Number 的类,并且所有具体类都与您可能想要做的一种方式进行比较如下:

@Override
public int compareTo(ComplexNumber o) {

    if (o.real  instanceof BigInteger && this.real instanceof BigInteger) {
        int realCompValue = ((BigInteger)(o.real)).compareTo((BigInteger)(this.real));
        if (realCompValue == 0 ) {
            return compareImaginaryVal(o.imaginary, this.imaginary);
        } else {
            return realCompValue;
        }
    } else if (o.real  instanceof BigDecimal && this.real instanceof BigDecimal) {
        int realCompValue = ((BigDecimal)(o.real)).compareTo((BigDecimal)(this.real));
        if (realCompValue == 0 ) {
            return compareImaginaryVal(o.imaginary, this.imaginary);
        } else {
            return realCompValue;
        }
    } 

    // After checking all the Number extended class...
    else {
        // Throw exception.
    }
}

private int compareImaginaryVal(Number imaginary2, U imaginary3) {
    // TODO Auto-generated method stub
    return 0;
}
于 2013-10-29T15:06:32.080 回答
0

试试看:

class ComplexNumber<T extends Number, U extends Number> implements Comparable<ComplexNumber<T, U>> {
  @Override
  public int compareTo(ComplexNumber<T, U> o) {
    return 0;
  }
}
于 2013-10-29T14:44:31.017 回答