jtulach@155: package api; jtulach@155: jtulach@155: import org.apidesign.runtime.check.RuntimeCheck; jtulach@155: jtulach@155: /** Class to simplify arithmetical operations, improved version to compute jtulach@155: * the sum for ranges, but only if the virtual machine is configured to jtulach@155: * run in incompatible mode. jtulach@155: * jtulach@155: * @author Jaroslav Tulach jtulach@155: * @version 2.0 jtulach@155: */ jtulach@155: public class Arithmetica { jtulach@155: public int sumTwo(int one, int second) { jtulach@155: return one + second; jtulach@155: } jtulach@155: jtulach@155: public int sumAll(int... numbers) { jtulach@187: if (numbers.length == 0) { jtulach@187: return 0; jtulach@187: } jtulach@155: int sum = numbers[0]; jtulach@155: for (int i = 1; i < numbers.length; i++) { jtulach@155: sum = sumTwo(sum, numbers[i]); jtulach@155: } jtulach@155: return sum; jtulach@155: } jtulach@155: jtulach@155: public int sumRange(int from, int to) { jtulach@155: if (calledByV2AwareLoader()) { jtulach@155: return sumRange2(from, to); jtulach@155: } else { jtulach@155: return sumRange1(from, to); jtulach@155: } jtulach@155: } jtulach@155: jtulach@155: private int sumRange1(int from, int to) { jtulach@155: int len = to - from; jtulach@210: if (len < 0) { jtulach@210: len = -len; jtulach@210: from = to; jtulach@210: } jtulach@155: int[] array = new int[len + 1]; jtulach@155: for (int i = 0; i <= len; i++) { jtulach@155: array[i] = from + i; jtulach@155: } jtulach@155: return sumAll(array); jtulach@155: } jtulach@155: jtulach@155: private int sumRange2(int from, int to) { jtulach@210: return (from + to) * (Math.abs(to - from) + 1) / 2; jtulach@155: } jtulach@155: jtulach@155: private static boolean calledByV2AwareLoader() { jtulach@155: // BEGIN: design.composition.arith2.6.runtime jtulach@155: StackTraceElement[] arr = Thread.currentThread().getStackTrace(); jtulach@155: ClassLoader myLoader = Arithmetica.class.getClassLoader(); jtulach@155: for (int i = 0; i < arr.length; i++) { jtulach@155: ClassLoader caller = arr[i].getClass().getClassLoader(); jtulach@155: if (myLoader == caller) { jtulach@155: continue; jtulach@155: } jtulach@155: if (RuntimeCheck.requiresAtLeast("2.6", "api.Arithmetica", caller)) { jtulach@155: return true; jtulach@155: } jtulach@155: return false; jtulach@155: } jtulach@155: return true; jtulach@155: // END: design.composition.arith2.6.runtime jtulach@155: } jtulach@155: jtulach@155: }