Main Page   Class Hierarchy   Alphabetical List   Compound List   File List   Compound Members  

Multiplier.java

Go to the documentation of this file.
00001 // file:    Multiplier.java
00002 // author:  Robert M. Keller
00003 // purpose: Example of a Function2 object
00004 
00005 /**
00006  * A Multiplier is a Function2 object that can be used to multiply a
00007  * pair of Numbers.  If both Numbers are Long or Integer, it returns a
00008  * Long.  Otherwise it returns a Double.
00009  */
00010 
00011 class Multiplier implements Function2
00012 {
00013 /**
00014  * Create a Multiplier with a specific scale factor.
00015  * @param _factor the factor to be used
00016  */
00017 
00018 Multiplier()
00019   {
00020   }
00021 
00022 
00023 /**
00024  * Apply this Multiplier object to two Objects, both of which should be Numbers.
00025  * If they are not numbers, a ClassCastException will be thrown.
00026  *
00027  * @param x the first argument of this function
00028  * @param y the second argument of this function
00029  * @return a Number containing the product of the arguments.  If the arguments
00030  * are both Integer or Long, it returns a Long.  Otherwise it returns a Double.
00031  */
00032 
00033 public Object apply(Object x, Object y)
00034   {
00035   return multiply(x, y);
00036   }
00037 
00038 
00039 /**
00040  * Multiply two Objects, both of which should be Numbers.
00041  * If they are not numbers, a ClassCastException will be thrown.
00042  *
00043  * @param x the first argument of this function
00044  * @param y the second argument of this function
00045  * @return a Number containing the product of the arguments.  If the arguments
00046  * are both Integer or Long, it returns a Long.  Otherwise it returns a Double.
00047  */
00048 
00049 public static Number multiply(Object x, Object y)
00050   {
00051   if( (x instanceof Long || x instanceof Integer)
00052    && (y instanceof Long || y instanceof Integer) )
00053     {
00054     long xValue = ((Number)x).longValue();
00055     long yValue = ((Number)y).longValue();
00056     return new Long(xValue*yValue);
00057     }
00058   else
00059     {
00060     double xValue = ((Number)x).doubleValue();
00061     double yValue = ((Number)y).doubleValue();
00062     return new Double(xValue*yValue);
00063     }
00064   }
00065 }

Generated at Wed Feb 19 23:28:36 2003 for OpenList by doxygen1.2.6 written by Dimitri van Heesch, © 1997-2001