我有一些代碼來找出不同數據類型(int,long,double)與BigInteger比較的操作的正確性。操作獲取一個數字的階乘,直到結果與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;
}
非常感謝提前。
我的建議是看一個case語句(https://docs.oracle.com/javase/tutorial/java /nutsandbolts/switch.html)如果你真的想用一種方法。有時候,具有獨特(和可讀)名稱的不同方法對乾淨代碼是最好的:) – Gorbles
一種選擇是使用'factorial(Number n)',但不能輕鬆寫出這一行'result = number * longFactorial (number - 1);'因爲在Java中沒有操作符重載... – assylias
是否可以使用java 8?如果是的話,那麼你可以通過創建一個接受相應的lambda函數(如乘法)的泛型方法來輕鬆實現這一點,然後爲每種情況指定這些函數。 – user3707125