gpt4 book ai didi

Java 未选中 : unchecked generic array creation for varargs parameter

转载 作者:IT老高 更新时间:2023-10-28 11:33:13 26 4
gpt4 key购买 nike

我已将 Netbeans 设置为在我的 Java 代码中显示未经检查的警告,但我无法理解以下几行中的错误:

private List<String> cocNumbers;
private List<String> vatNumbers;
private List<String> ibans;
private List<String> banks;
...
List<List<String>> combinations = Utils.createCombinations(cocNumbers, vatNumbers, ibans);

给予:

[unchecked] unchecked generic array creation for varargs parameter of type List<String>[]

方法来源:

/**
* Returns a list of all possible combinations of the entered array of lists.
*
* Example: [["A", "B"], ["0", "1", "2"]]
* Returns: [["A", "0"], ["A", "1"], ["A", "2"], ["B", "0"], ["B", "1"], ["B", "2"]]
*
* @param <T> The type parameter
* @param elements An array of lists
* @return All possible combinations of the entered lists
*/
public static <T> List<List<T>> createCombinations(List<T>... elements) {
List<List<T>> returnLists = new ArrayList<>();

int[] indices = new int[elements.length];
for (int i = 0; i < indices.length; i++) {
indices[i] = 0;
}

returnLists.add(generateCombination(indices, elements));
while (returnLists.size() < countCombinations(elements)) {
gotoNextIndex(indices, elements);
returnLists.add(generateCombination(indices, elements));
}

return returnLists;
}

究竟出了什么问题,我将如何解决它,因为我认为在代码中留下未经检查的警告不是一个好主意?

忘了提,但我使用的是 Java 7。

编辑:我现在还看到该方法具有以下内容:

[unchecked] Possible heap pollution from parameterized vararg type List<T>
where T is a type-variable:
T extends Object declared in method <T>createCombinations(List<T>...)

最佳答案

正如上面提到的 janoh.janoh,Java 中的 varargs 只是数组的语法糖加上在调用站点隐式创建的数组。所以

List<List<String>> combinations =
Utils.createCombinations(cocNumbers, vatNumbers, ibans);

其实是

List<List<String>> combinations =
Utils.createCombinations(new List<String>[]{cocNumbers, vatNumbers, ibans});

但您可能知道,new List<String>[]在 Java 中是不允许的,原因已在许多其他问题中介绍过,但主要与数组在运行时知道其组件类型这一事实有关,并在运行时检查添加的元素是否与其组件类型匹配,但此检查是不能用于参数化类型。

无论如何,编译器仍然会创建数组,而不是失败。它做了类似的事情:

List<List<String>> combinations =
Utils.createCombinations((List<String>[])new List<?>[]{cocNumbers, vatNumbers, ibans});

这可能不安全,但不一定不安全。大多数可变参数方法只是遍历可变参数元素并读取它们。在这种情况下,它不关心数组的运行时类型。您的方法就是这种情况。由于您使用的是 Java 7,因此您应该添加 @SafeVarargs注释到您的方法,您将不会再收到此警告。这个注解基本上说,这个方法只关心元素的类型,而不关心数组的类型。

但是,有一些可变参数方法确实使用了数组的运行时类型。在这种情况下,它可能是不安全的。这就是警告存在的原因。

关于Java 未选中 : unchecked generic array creation for varargs parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21132692/

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