2013-10-29 54 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; 
}