2016-09-14 6 views
-3

ジェネリックの概念を理解するのが難しいです。クラスDataSetを汎用フォームに変換する必要があります。私は特に、DataSetのフィールドで何をするのか分からない。ここで 私が思いついたのソリューションです:私はGenericクラスに変換する

/** 
    Computes the average of a set of data values. 
*/ 
public class DataSet 
{ 
    private double sum; 
    private Measurable maximum; 
    private int count; 

    /** 
    Constructs an empty data set. 
    */ 
    public DataSet() 
    { 
     sum = 0; 
     count = 0; 
     maximum = null; 
    } 

    /** 
     Adds a data value to the data set. 
     @param x a data value 
    */ 
    public void add(Measurable x) 
    { 
     sum = sum + x.getMeasure(); 
     if (count == 0 || maximum.getMeasure() <  x.getMeasure()) 
      maximum = x; 
     count++; 
     } 

    /** 
     Gets the average of the added data. 
     @return the average or 0 if no data has been added 
    */ 
    public double getAverage() 
    { 
     if (count == 0) return 0; 
     else return sum/count; 
    } 

    /** 
     Gets the largest of the added data. 
     @return the maximum or 0 if no data has been added 
    */ 
    public Measurable getMaximum() 
    { 
     return maximum; 
    } 
} 

アップデートは、我々はT.ですべての署名を代用する必要があることを理解して自分自身に質問を尋ねることによって

public class DataSetGen <T> 
{ 
    private double sum; 
    private T maximum; 
    private int count; 

    /** 
     Constructs an empty data set. 
    */ 
    public DataSetGen() 
    { 
     sum = 0; 
     count = 0; 
     maximum = null; 
    } 

    /** 
     Adds a data value to the data set. 
     @param x a data value 
    */ 
    public void add(T x) 
    { 
     sum = sum + x.getMeasure(); 
     if (count == 0 || maximum.getMeasure() < x.getMeasure()) 
     maximum = x; 
     count++; 
    } 

    /** 
     Gets the average of the added data. 
     @return the average or 0 if no data has been added 
    */ 
    public double getAverage() 
    { 
     if (count == 0) return 0; 
     else return sum/count; 
    } 

    /** 
     Gets the largest of the added data. 
     @return the maximum or 0 if no data has been added 
    */ 
    public T getMaximum() 
    { 
     return maximum; 
    } 
} 
+0

これまでに何を試しましたか?通常、ジェネリッククラスは 'public class DataSet 'のように定義され、 'public void add(T x)'やプライベート変数 'private T maximum;'のように、 'T'で追加するオブジェクトのインスタンスをすべて置き換えます。 – Orin

+0

おそらく、 'DataSet 'を使い、 'Measurable'を' T'で置き換えてください。 'getMaximum()'の戻り値型の目的は、より良い型にすることができます。 – Andreas

+0

私はちょうど私の答えを更新しました。私が正しいかどうかわからない –

答えて

0

スタート「これが想定しています???の集合である "。あなたの場合、それはおそらくMeasurableのサブクラスのセットです。

これで、ジェネリック型をどこに配置すればよいか分かりました。

+0

私はそれを理解したかどうかはわかりません。 –

+0

私は自分の答えを更新しました。私は追加する必要があると思う:public class DataSetGen

関連する問題