Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Created September 22, 2021 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomasdarimont/6113e6dd4b36ef51c5bd31646dec6eba to your computer and use it in GitHub Desktop.
Save thomasdarimont/6113e6dd4b36ef51c5bd31646dec6eba to your computer and use it in GitHub Desktop.
Example for using static in a local class for memoization
package wb.java17;
import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class StaticsInLocalClassesExample {
public static void main(String[] args) {
System.out.println(factorial(120));
System.out.println(factorial(120));
System.out.println(factorial(121));
}
static BigInteger factorial(int n) {
class Local {
private static final Map<Integer, BigInteger> CACHE = new ConcurrentHashMap<>();
}
if (n == 0) {
return BigInteger.ONE;
}
var nn = Local.CACHE.get(n);
if (nn != null) {
return nn;
}
var result = BigInteger.valueOf(n).multiply(factorial(n - 1));
Local.CACHE.put(n, result);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment