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的时候,在原始类型和对象之间还要进行小小的转换.