有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用泛型类型时出现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) 个答案

  1. # 1 楼答案

    add单个元素添加到列表中。如果调用成功,它将向列表中添加一个数组引用,而不是数组的内容,然后列表将包含一个元素(即引用)

    假设出于某种原因希望保留现有的代码结构(而不是在循环中单独添加元素):

    要将数组的内容添加到列表中,请使用Arrays.asList将数组“包装”在List中,然后使用addAll

    recyclingCrates.addAll(Arrays.asList(houses));
    

    您还需要将houses的类型更改为Integer[],否则,Arrays.asList将需要返回List<int>,这是不可能的。(您也可以将其用作Arrays.asList(thing1, thing2, thing3)返回一个包含thing1things2thing3的列表,将使用此语法,返回一个仅包含单个数组引用的列表,该列表将返回到您开始的位置!)