Duck typing alows true polymorfisim

The Ghost In The Machine ewill at sirius.tg00suus7038.net
Fri Aug 25 18:00:04 EDT 2006


In comp.lang.java.advocacy, atbusbook at aol.com
<atbusbook at aol.com>
 wrote
on 25 Aug 2006 12:05:21 -0700
<1156532721.879808.40990 at i3g2000cwc.googlegroups.com>:
> lets say you want a generic numerical algorithom like sum
>
> Ruby
>
> def sum lst
>   lst.inject(0){|total,current| total*current}
> end
>
> Java // i dont know if there is a numeric super class for numbers
>
> class Sum{
>   public static int sum(int[] lst){
>     int total = 0;
>     for(int current : lst){
>       total+=current;
>     }
>     return total;
>   }
>   // repeat for all other number types
> }
>

There isn't; Java makes the distinction between an int and
an Integer, a double and a Double.  Java 5 did introduce
autoboxing, which makes things like

Number[] numbers = new Number[]{1, 2.3, 4, 5.6};

possible, and Number is a baseclass for both Integer and
Double (but not int and double).

Therefore, one could write:

public class Sum {
  public static double sum(int[] lst)
  {
    Number[] nlst = new Number[lst.length];
    for(int i = 0; i < nlst.length; i++) nlst[i] = new Integer(lst[i]);
    return sum(Arrays.asList(nlst));
  }
  public static double sum(double[] lst)
  {
    Number[] nlst = new Number[lst.length];
    for(int i = 0; i < nlst.length; i++) nlst[i] = new Double(lst[i]);
    return sum(Arrays.asList(nlst));
  }
  public static double sum(float[] lst)
  {
    Number[] nlst = new Number[lst.length];
    for(int i = 0; i < nlst.length; i++) nlst[i] = new Double(lst[i]);
    return sum(Arrays.asList(nlst));
  }
  public static double sum(Number[] lst)
  {
    return sum(Arrays.asList(lst));
  }
  public static double sum(Collection<Number> lst)
  {
    double sum = 0;
    for(Iterator<Number> i = lst.iterator(); i.hasNext())
      sum += i.next().doubleValue();
    return sum;
  }

}

A rather ugly but possibly useful duckling.

-- 
#191, ewill3 at earthlink.net
Windows Vista.  Because it's time to refresh your hardware.  Trust us.



More information about the Python-list mailing list