title: Creating a User Defined Aggregate function in Apache Derby
body: <p>I need to create a User Defined Aggregate (UDA) function in Derby (specifically, a <code>Variance</code> function), but I'm kinda stuck with the proper way to write it.</p>
  
  <p>So far, I have the "template" for the UDA:</p>
  
  <pre><code>public class Variance&lt;V extends Comparable&lt;V&gt;&gt; implements Aggregator&lt;V,V,Variance&lt;V&gt;&gt; {
      private ArrayList&lt;V&gt; _values;
      public Variance() {/*Empty constructor*/}
      public void init() {_values = new ArrayList&lt;V&gt;(); }
      public void accumulate(V v) { _values.add(v); }
      public void merge(Variance&lt;V&gt; o) { _values.addAll(o._values); }
      public V terminate() {
          // Here is my issue!!!
      }
  }
  </code></pre>
  
  <p>The issue I'm facing is this: To compute the variance I need to calculate something like this:</p>
  
  <pre><code>V sum, sumSq;
  int n = _values.size();
  if(n &lt;= 0)
      return null;
  // Initialize sum and sumSq to "zero"
  for(V v : _values) {
      sum += v; // Or somehow add v to sum
      sumSq += Math.pow(v, 2); // Or somehow add (v^2) to sumSq
  }
  return (sumSq - n * Math.pow(sum / n, 2)) / n;
  </code></pre>
  
  <p>... but I don't know how to tell that this is only valid for numeric types (integer, decimal or floating-point values).</p>
  
  <p>I think I'm missing something in my code, but I don't know if there's a way to tell this program that <code>V</code> is numeric, and thus, I can use arithmetic operations on values of type <code>V</code>.</p>
  
  <p>So, the specific questions are: </p>
  
  <ul>
  <li>Is there a way to perform this operations (addition, substraction, product, power) on the values?</li>
  <li>Should I change the definition of <code>V</code> (somewhat making it extend a "numeric" class, like <code>Double</code>)?</li>
  </ul>