我已将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;
}
到底哪里出了问题,我该如何修复它,因为我认为在代码中留下未经检查的警告不是一个好主意?
忘了提一下,我使用的是Java7。
编辑:我现在还看到该方法有以下几点:
[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>...)
发布于 2014-01-16 07:42:13
如上所述,janoh.janoh中的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});
这可能是不安全的,但不一定不安全。大多数varargs方法只是简单地迭代varargs元素并读取它们。在这种情况下,它并不关心数组的运行时类型。您的方法就是这种情况。由于您使用的是Java7,因此应该将@SafeVarargs
注释添加到您的方法中,并且不会再收到此警告。这个注解基本上是说,这个方法只关心元素的类型,而不关心数组的类型。
但是,有些varargs方法确实使用数组的运行时类型。在这种情况下,它可能是不安全的。这就是警告存在的原因。
发布于 2014-01-15 18:58:01
因为java编译器对varargs使用隐式数组创建,而java不允许泛型数组创建(因为类型参数是不可重复的)。
以下代码是正确的(数组允许执行这些操作),因此需要未选中的警告:
public static <T> List<List<T>> createCombinations(List<T> ... lists) {
((Object[]) lists)[0] = new ArrayList<Integer>();
// place your code here
}
查看全面的解释here
https://stackoverflow.com/questions/21132692
复制相似问题