2013-10-29 52 views
0

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

  1. ComplexNumber(T real, U imaginary) - 构造
  2. getReal():T
  3. getImaginary():U
  4. modul():double - 这是复杂的模数
  5. compareTo(ComplexNumber<?, ?> o) - 此方法使得根据2个复数
模量比较

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

这里是我的代码:help here - 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 
    } 




} 

有人用这种方法帮助吗?

+2

如果'T'和'U'都是'Number',只需声明它们,而不是使用泛型。 –

+0

它应该具有与当前复数相同的类型,它是'ComplexNumber ' –

回答

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

试试:

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