Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save domix/f649ce9c084f03a29996c3f9a77595b9 to your computer and use it in GitHub Desktop.
Save domix/f649ce9c084f03a29996c3f9a77595b9 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;
}
}
@domix
Copy link
Author

domix commented Jun 10, 2024

orale

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment