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里面是否緩存了這個要害字-參數(shù)n,假如找到了,就直接返回這個值.否則,就會進(jìn)行這個冗長的計算,并將結(jié)果保存到緩存里面.在添加進(jìn)HashMap的時候,在原始類型和對象之間還要進(jìn)行小小的轉(zhuǎn)換.