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