2017-11-11 122 views
0

所以我試圖做一個簡單的程序,可以找到一個複雜的使用數量泛型的模塊,並比較兩個模塊:錯誤而比較兩種方法

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()); 
    } 
} 

但是它給了我兩個實時一個錯誤在.compareTo功能說明:

,一個在類的開頭「的基本類型雙不能調用的compareTo(雙)」:「在這一行 多個標記 - 類型ComplexNumber必須實現繼承的抽象方法 Comparable> .compareTo(ComplexNumber) - Typ ËComplexNumber必須實現繼承的抽象方法「

回答

1

你要找的線沿線的東西:

@Override 
public int compareTo(ComplexNumber<T, U> o) { 
     // logic 
} 

編輯

,如果你一定要使用通配符,那麼你就需要將類別聲明更改爲:

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

在這種情況下,您可以將compareTo方法簽名原樣。

關於您收到的第一個錯誤,這是因爲您正試圖在基本類型double上調用compareTo方法,這根本不起作用。要解決此問題,您需要使用Double.compare並傳入相應的數據。

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

不能這樣做。它說在方法中必須使用通配符。 –

+0

誰說的..? –

+0

在我的assigment它說我需要使用通配符。 –