gpt4 book ai didi

java - 将几种方法组合成唯一的一种。泛型

转载 作者:行者123 更新时间:2023-11-29 05:04:44 24 4
gpt4 key购买 nike

我有一些代码可以确定与 BigInteger 相比,对不同数据类型(int、long、double)的操作的正确性。操作是获取数字的阶乘,直到结果与 BigInteger 相同。

问题是我如何更改我的代码,使其更通用、紧凑和干净?我怎么能得到唯一的一种方法,而不是 4 种不同类型的方法?此方法中的逻辑和流程几乎相同。

代码(没有比较逻辑)是:

private static HashMap<BigInteger, BigInteger> bigIntegerFactorials = new HashMap<>();
private static BigInteger bigIntegerFactorial(BigInteger number) {
if (number.equals(BigInteger.ONE)) {
return BigInteger.ONE;
}
BigInteger result = bigIntegerFactorials.get(number);
if (result == null) {
result = number.multiply(bigIntegerFactorial(number.subtract(BigInteger.ONE)));
bigIntegerFactorials.put(number, result);
}
return result;
}

private static HashMap<Integer, Integer> intFactorials = new HashMap<>();
private static int intFactorial(int number) {
if (number == 1) {
return 1;
}
Integer result = intFactorials.get(number);
if (result == null) {
result = number * intFactorial(number - 1);
intFactorials.put(number, result);
}
return result;
}

private static HashMap<Long, Long> longFactorials = new HashMap<>();
private static long longFactorial(long number) {
if (number == 1) {
return 1L;
}
Long result = longFactorials.get(number);
if (result == null) {
result = number * longFactorial(number - 1);
longFactorials.put(number, result);
}
return result;
}

private static HashMap<Double, Double> doubleFactorials = new HashMap<>();
private static double doubleFactorial(double number) {
if (number == 1) {
return 1.;
}
Double result = doubleFactorials.get(number);
if (result == null) {
result = number * doubleFactorial(number - 1);
doubleFactorials.put(number, result);
}
return result;
}

非常感谢。

最佳答案

您可以将乘法和减量函数传递给通用方法:

private static Map<Number, Number> factorials = new HashMap<> ();

private static <T extends Number> T factorial(T n, BinaryOperator<T> multiply, UnaryOperator<T> decrement) {
if (n.doubleValue() == 1) return n;
T result = (T) factorials.get(n);
if (result == null ){
result = multiply.apply(n, factorial(decrement.apply(n), multiply, decrement));
factorials.put(n, result);
}
return result;
}

然后你可以像这样改变你的原始方法:

public static int intFactorial(int number) {
return factorial(number, (i, j) -> i * j, i -> i - 1);
}

警告:此方法似乎会使 Netbeans 崩溃,但可以使用 javac 正常编译...

关于java - 将几种方法组合成唯一的一种。泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30754600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com