Search code examples
javagenericsgeneric-programming

Converting into Generic class


I have trouble understanding generics concept. I need to convert class DataSet into its generic form. I especially don't get what to do with the fields of DataSet. I do understand that we have to substitute all the signatures with 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;
   }
}

Update: Here is the solution i came up with:

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

Solution

  • Start by asking yourself the question "This is supposed to be a set of ???". In your case, it's probably a set of a subclass of Measurable.

    Now that you have this, you should be able to work out where to put the generic types.