1 33 package net.sf.jga.fn.arithmetic; 34 35 import java.text.MessageFormat ; 36 import java.util.Iterator ; 37 import net.sf.jga.fn.UnaryFunctor; 38 39 46 47 public class Average<T extends Number > extends UnaryFunctor<Iterator <T>,T> { 48 49 static final long serialVersionUID = -8341653586442484621L; 50 51 private Arithmetic<T> _math; 54 55 58 public Average(Class <T> type) { 59 _math = ArithmeticFactory.getArithmetic(type); 60 if (_math == null) { 61 String msg = "No implementation of Arithmetic registered for {0}"; 62 throw new IllegalArgumentException (MessageFormat.format(msg, new Object []{type})); 63 } 64 } 65 66 69 public T fn (Iterator <T> iterator) { 70 int count = 0; 71 T sum = _math.zero(); 72 73 while (iterator.hasNext()) { 74 T value = iterator.next(); 75 sum = _math.plus(sum, value); 76 ++count; 77 } 78 79 return _math.divides(sum, _math.valueOf(count)); 80 } 81 82 86 public void accept(net.sf.jga.fn.Visitor v) { 87 if (v instanceof Average.Visitor) 88 ((Average.Visitor)v).visit(this); 89 else 90 v.visit(this); 91 } 92 93 95 public String toString() { 96 return "Average[]"; 97 } 98 99 101 104 public interface Visitor extends net.sf.jga.fn.Visitor { 105 public void visit(Average host); 106 } 107 } 108 | Popular Tags |