samples/composition/src-api2.0-runtime/org/apidesign/math/Arithmetica.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Feb 2009 17:30:06 +0100
changeset 321 06bf3a32eaa0
parent 210 samples/composition/src-api2.0-runtime/api/Arithmetica.java@acf2c31e22d4
child 323 4e59b6b0e907
permissions -rw-r--r--
Moving code to org.apidesign.math package
     1 package org.apidesign.math;
     2 
     3 import org.apidesign.math.Arithmetica;
     4 import org.apidesign.runtime.check.RuntimeCheck;
     5 
     6 /** Class to simplify arithmetical operations, improved version to compute
     7  * the sum for ranges, but only if the virtual machine is configured to
     8  * run in incompatible mode.
     9  *
    10  * @author Jaroslav Tulach <jtulach@netbeans.org>
    11  * @version 2.0
    12  */
    13 public class Arithmetica {
    14     public int sumTwo(int one, int second) {
    15         return one + second;
    16     }
    17     
    18     public int sumAll(int... numbers) {
    19         if (numbers.length == 0) {
    20             return 0;
    21         }
    22         int sum = numbers[0];
    23         for (int i = 1; i < numbers.length; i++) {
    24             sum = sumTwo(sum, numbers[i]);
    25         }
    26         return sum;
    27     }
    28     
    29     public int sumRange(int from, int to) {
    30         if (calledByV2AwareLoader()) {
    31             return sumRange2(from, to);
    32         } else {
    33             return sumRange1(from, to);
    34         }
    35     }
    36 
    37     private int sumRange1(int from, int to) {
    38         int len = to - from;
    39         if (len < 0) {
    40             len = -len;
    41             from = to;
    42         }
    43         int[] array = new int[len + 1];
    44         for (int i = 0; i <= len; i++) {
    45             array[i] = from + i;
    46         }
    47         return sumAll(array);
    48     }
    49     
    50     private int sumRange2(int from, int to) {
    51         return (from + to) * (Math.abs(to - from) + 1) / 2;
    52     }
    53 
    54     private static boolean calledByV2AwareLoader() {
    55         // BEGIN: design.composition.arith2.6.runtime
    56         StackTraceElement[] arr = Thread.currentThread().getStackTrace();
    57         ClassLoader myLoader = Arithmetica.class.getClassLoader();
    58         for (int i = 0; i < arr.length; i++) {
    59             ClassLoader caller = arr[i].getClass().getClassLoader();
    60             if (myLoader == caller) {
    61                 continue;
    62             }
    63             if (RuntimeCheck.requiresAtLeast("2.6", "api.Arithmetica", caller)) {
    64                 return true;
    65             }
    66             return false;
    67         }
    68         return true;
    69         // END: design.composition.arith2.6.runtime
    70     }
    71     
    72 }