ArrayList的错误使用泛型类型
问题描述:
当在运行下面的代码,我得到的错误:ArrayList的错误使用泛型类型
add(java.lang.Integer) in ArrayList cannot be applied to java.lang.Integer[]
如果我不ArrayList中使用泛型类型,它运行得很好。我不明白这个错误,因为arrayList和数组都是整数。我错过了什么?谢谢!
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
答
add
添加单个元件到列表中。如果你的调用成功了,它会为列表添加一个数组引用 - 而不是数组的内容 - 然后列表将包含一个元素(这是引用)。
假设你想保持现有的代码结构,由于某种原因(而不是单独增加循环内的元素):
要添加阵列的内容到列表中,使用Arrays.asList
为“包裹”在List
数组,然后使用addAll
:
recyclingCrates.addAll(Arrays.asList(houses));
您还需要改变houses
到Integer[]
类型 - 否则,Arrays.asList
将需要返回List<int>
,这是不可能的。 (您也可以使用它作为Arrays.asList(thing1, thing2, thing3)
返回包含thing1
,things2
和thing3
名单 - 这句法将被用来代替,返回一个只包含数组引用的列表,这将是回到你开始的地方!)
所以你认为'int []'和'Integer'是一样的吗?或者你认为'ArrayList'与'int []'是一样的吗?你读过'ArrayList#add'的javadoc吗? –
2015-02-09 01:15:20
注意:您的代码存在此问题未涉及的其他问题。我认为它不会给你你期望的结果,即使在解决这个问题之后。 – immibis 2015-02-09 01:16:55