gpt4 book ai didi

java - 私有(private)函数应该如何做参数验证或者用户输入和内部数据结构?

转载 作者:行者123 更新时间:2023-12-02 06:24:24 26 4
gpt4 key购买 nike

以下代码将返回总和为 x 的整数对,例如:如果 arr {1, 2, 3, 4, 5] 且 x 为 7,则列表应包含 {3, 4} 和 {2, 5 }。主要目标是了解如何在私有(private)方法中执行参数验证。问题嵌套在评论中,请将建议限制为仅提出的问题。感谢您深入研究代码来检查我的问题。

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);
}
}
}

最佳答案

QUESTION 1: Should check of "all positive integers" be done here too ?

答:不;因为您将在 getPair() 之前调用 getPairsFromPositiveArray() 来获取列表

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 ?

答:断言

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

答:

  • 始终执行健全性检查...所以是的,请检查 arr != null

  • 总是更喜欢断言而不是抛出 NPE

关于java - 私有(private)函数应该如何做参数验证或者用户输入和内部数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20697820/

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