使用泛型类型时出现ArrayList错误



当运行以下代码时,我得到错误:

ArrayList中的add(java.lang.Integer)不能应用于java.lang.Interger[]

如果我在ArrayList中不使用泛型类型,它运行得很好。我真的不理解这个错误,因为arrayList和数组都是Integers。我错过了什么?非常感谢。

        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)来返回包含thing1things2thing3的列表,而将使用此语法,返回仅包含单个数组引用的列表,该列表将返回到您开始的位置!)

最新更新