2015-02-09 233 views
-1

當在運行下面的代碼,我得到的錯誤: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 
+0

所以你認爲'int []'和'Integer'是一樣的嗎?或者你認爲'ArrayList '與'int []'是一樣的嗎?你讀過'ArrayList#add'的javadoc嗎? – 2015-02-09 01:15:20

+1

注意:您的代碼存在此問題未涉及的其他問題。我認爲它不會給你你期望的結果,即使在解決這個問題之後。 – immibis 2015-02-09 01:16:55

回答

1

add添加單個元件到列表中。如果你的調用成功了,它會爲列表添加一個數組引用 - 而不是數組的內容 - 然後列表將包含一個元素(這是引用)。

假設你想保持現有的代碼結構,由於某種原因(而不是單獨增加循環內的元素):

要添加陣列的內容到列表中,使用Arrays.asList爲「包裹」在List數組,然後使用addAll

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

您還需要改變housesInteger[]類型 - 否則,Arrays.asList將需要返回List<int>,這是不可能的。 (您也可以使用它作爲Arrays.asList(thing1, thing2, thing3)返回包含thing1things2thing3名單 - 這句法將被用來代替,返回一個只包含數組引用的列表,這將是回到你開始的地方!)

+0

啊,這將解釋爲什麼我的代碼似乎工作後,我這樣做:for(int x = 0; x <8; x ++)System.out.println(「多少個回收箱設置在家裏」+ x +「?」); houses [x] = scanner.nextInt(); recyclingCrates.add(houses [x]); } 知道它只增加了一個元素使得更清晰的事情,謝謝! – Michelle 2015-02-09 01:20:27

+0

@SotiriosDelimanolis oops,我認爲這是一個Integer [],因爲這是引用的錯誤消息說的。 – immibis 2015-02-09 01:20:42