【问题标题】:ArrayList error when using Generic Types使用泛型类型时出现 ArrayList 错误
【发布时间】:2015-02-09 01:14:26
【问题描述】:

运行以下代码时,出现错误:

ArrayList 中的add(java.lang.Integer) 不能应用于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

【问题讨论】:

  • 所以您认为int[]Integer 相同?还是您认为ArrayList&lt;Integer&gt;int[] 相同?你读过ArrayList#add的javadoc吗?
  • 注意:您的代码存在此问题未涵盖的其他问题。我不认为它会给你你期望的结果,即使在解决了 this 问题之后。

标签: java generics arraylist


【解决方案1】:

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

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

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

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

您还需要将houses 的类型更改为Integer[] - 否则,Arrays.asList 需要返回List&lt;int&gt;,这是不可能的。 (您也可以将其用作 Arrays.asList(thing1, thing2, thing3) 以返回包含 thing1things2thing3 的列表 - 并且将使用此语法,返回仅包含单个数组引用的列表,该列表将返回你从哪里开始的!)

【讨论】:

  • 啊,这可以解释为什么我的代码在我这样做之后似乎可以工作: for (int x = 0; x
  • @SotiriosDelimanolis 哎呀,我认为它是一个 Integer[] 因为这是引用的错误消息所说的。
猜你喜欢
  • 2012-06-29
  • 1970-01-01
  • 1970-01-01
  • 2015-10-04
  • 2020-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多