Created
September 22, 2021 15:29
-
-
Save thomasdarimont/6113e6dd4b36ef51c5bd31646dec6eba to your computer and use it in GitHub Desktop.
Example for using static in a local class for memoization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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