1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/samples/composition/src-api2.0-runtime/org/apidesign/math/Arithmetica.java Sat Feb 14 17:30:06 2009 +0100
1.3 @@ -0,0 +1,72 @@
1.4 +package org.apidesign.math;
1.5 +
1.6 +import org.apidesign.math.Arithmetica;
1.7 +import org.apidesign.runtime.check.RuntimeCheck;
1.8 +
1.9 +/** Class to simplify arithmetical operations, improved version to compute
1.10 + * the sum for ranges, but only if the virtual machine is configured to
1.11 + * run in incompatible mode.
1.12 + *
1.13 + * @author Jaroslav Tulach <jtulach@netbeans.org>
1.14 + * @version 2.0
1.15 + */
1.16 +public class Arithmetica {
1.17 + public int sumTwo(int one, int second) {
1.18 + return one + second;
1.19 + }
1.20 +
1.21 + public int sumAll(int... numbers) {
1.22 + if (numbers.length == 0) {
1.23 + return 0;
1.24 + }
1.25 + int sum = numbers[0];
1.26 + for (int i = 1; i < numbers.length; i++) {
1.27 + sum = sumTwo(sum, numbers[i]);
1.28 + }
1.29 + return sum;
1.30 + }
1.31 +
1.32 + public int sumRange(int from, int to) {
1.33 + if (calledByV2AwareLoader()) {
1.34 + return sumRange2(from, to);
1.35 + } else {
1.36 + return sumRange1(from, to);
1.37 + }
1.38 + }
1.39 +
1.40 + private int sumRange1(int from, int to) {
1.41 + int len = to - from;
1.42 + if (len < 0) {
1.43 + len = -len;
1.44 + from = to;
1.45 + }
1.46 + int[] array = new int[len + 1];
1.47 + for (int i = 0; i <= len; i++) {
1.48 + array[i] = from + i;
1.49 + }
1.50 + return sumAll(array);
1.51 + }
1.52 +
1.53 + private int sumRange2(int from, int to) {
1.54 + return (from + to) * (Math.abs(to - from) + 1) / 2;
1.55 + }
1.56 +
1.57 + private static boolean calledByV2AwareLoader() {
1.58 + // BEGIN: design.composition.arith2.6.runtime
1.59 + StackTraceElement[] arr = Thread.currentThread().getStackTrace();
1.60 + ClassLoader myLoader = Arithmetica.class.getClassLoader();
1.61 + for (int i = 0; i < arr.length; i++) {
1.62 + ClassLoader caller = arr[i].getClass().getClassLoader();
1.63 + if (myLoader == caller) {
1.64 + continue;
1.65 + }
1.66 + if (RuntimeCheck.requiresAtLeast("2.6", "api.Arithmetica", caller)) {
1.67 + return true;
1.68 + }
1.69 + return false;
1.70 + }
1.71 + return true;
1.72 + // END: design.composition.arith2.6.runtime
1.73 + }
1.74 +
1.75 +}