下面的代碼將返回總和爲x的整數對,例如:if arr {1,2,3,4,5]並且x是7,那麼list應該包含{3,4}和{2,5} 。主要目標是瞭解如何以私有方法執行參數驗證。問題嵌套在評論中,請僅對提出的問題提出建議。感謝您在代碼中檢查我的問題。私有函數應該如何進行參數驗證或用戶輸入以及內部數據結構?
public static List<Pair> getPairsFromPositiveArray(int[] arr, int x) {
// check for all positive integers
for (int i : arr) { // if arr is null, then this loop would throw NPE. So no need to make an exclicit check for null.
if (i < 0) throw new IllegalArgumentException("No integer should be negative.");
}
final List<Pair> list = new ArrayList<Pair>();
getPair(arr, x, list);
return list;
}
private static void getPair(int[] arr, int x, List<Pair> list) {
// QUESTION 1: Should check of "all positive integers" be done here too ?
/*
* QUESTION 2:
* list is data structure which we created internally (user did not provide it)
* Does anyone suggest, it throw an NPE or do an explicit assert check for list != null ?
*/
assert list != null; // form my understanding of e effective java.
assert arr != null; // form my understanding of e effective java.
final Set<Integer> set = new HashSet<Integer>();
/*
* QUESTION 3:
* arr is a data structure which was input by the user.
* Should we check for assert arr != null or let loop throw a NPE ?
*/
for (int i : arr) {
if (set.contains(i)) {
System.out.println(i + " : ");
list.add(new Pair(i, x - i));
} else {
set.add(x - i);
}
}
}
〜「形成我對e的理解」。你需要檢查你的語法。 –