使用泛型类型时出现java ArrayList错误
当运行以下代码时,我得到了错误:
add(java.lang.Integer) in ArrayList cannot be applied to java.lang.Integer[]
如果我在ArrayList中不使用泛型类型,它运行得很好。我不太理解这个错误,因为arrayList和array都是整数。我错过了什么?谢谢!
ArrayList<Integer> recyclingCrates = new ArrayList<Integer>();
int houses[] = new int[8];
int sum = 0;
for (int x = 0; x < 8; x++) {
System.out.println("How many recycling crates were set out at house " + x + "?");
houses[x] = scanner.nextInt();
for (Integer n : recyclingCrates){
houses[x]=n;
}
}
recyclingCrates.add(houses); //this is where I get the error
# 1 楼答案
add
将单个元素添加到列表中。如果调用成功,它将向列表中添加一个数组引用,而不是数组的内容,然后列表将包含一个元素(即引用)假设出于某种原因希望保留现有的代码结构(而不是在循环中单独添加元素):
要将数组的内容添加到列表中,请使用
Arrays.asList
将数组“包装”在List
中,然后使用addAll
:您还需要将
houses
的类型更改为Integer[]
,否则,Arrays.asList
将需要返回List<int>
,这是不可能的。(您也可以将其用作Arrays.asList(thing1, thing2, thing3)
返回一个包含thing1
、things2
和thing3
的列表,将使用此语法,返回一个仅包含单个数组引用的列表,该列表将返回到您开始的位置!)