转换为通用类

时间:2016-09-14 20:39:49

标签: java generics generic-programming

我无法理解泛型概念。我需要将类DataSet转换为其通用形式。我特别不知道如何处理DataSet的字段。我明白我们必须用T替换所有签名。

/**
   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;
   }
}

更新: 这是我提出的解决方案:

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

1 个答案:

答案 0 :(得分:0)

首先问问自己问题&#34;这应该是一组???&#34;。在您的情况下,它可能是一组Measurable的子类。

现在您已经拥有了这个,您应该能够找出放置泛型类型的位置。