实现比较使用通配符泛型



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

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

我已经实现了所有这些方法,除了最后一个,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 
    }


}

有人帮助这种方法吗?

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

@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<?, ?>>

试试看:

class ComplexNumber<T extends Number, U extends Number> implements Comparable<ComplexNumber<T, U>> {
  @Override
  public int compareTo(ComplexNumber<T, U> o) {
    return 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;
}

最新更新