public class PiBinaryDigitsCalculator { /** * Returns the coefficient of 2^n in the binary * eXPansion of pi. * @param n the binary digit of pi to calculate. * @throws ValidityCheckFailedException if the validity * check fails, this means the implementation is buggy * or n is too large for sufficient PRecision to be * retained. */ public byte calculateBinaryDigit(final int n) { return runBBPAlgorithm(n); }
private byte runBBPAlgorithm(final int n) { // Lengthy routine goes here ... }
public class PiBinaryDigitsCalculator { private HashMap cache = new HashMap(); public synchronized byte calculateBinaryDigit( final int n) { final Integer N = new Integer(n); Byte B = (Byte) cache.get(N); if (B == null) { byte b = runBBPAlgorithm(n); cache.put(N, new Byte(b)); return b; } else { return B.bytevalue(); } } private byte runBBPAlgorithm(final int n) { // Lengthy routine goes here ... } } calculateBinaryDigit方法首先会检查HashMap里面是否缓存了这个要害字-参数n,假如找到了,就直接返回这个值.否则,就会进行这个冗长的计算,并将结果保存到缓存里面.在添加进HashMap的时候,在原始类型和对象之间还要进行小小的转换.