2013-04-23 36 views
0

ArrayList的自定義類的有沒有。新增()方法:的Java - 自定義類的ArrayList沒有add方法

我可以定義對象的的ArrayList:

ArrayList<Object> thing = new ArrayList<Object>(); 


thing.add(otherThing); // works 

然而,當我定義的列表自定義類的東西事物:

ArrayList<Thing> thing = new ArrayList<Thing>(); 


thing.add(otherThing); // error 


Canvas.java:33: cannot find symbol 
symbol : method add(java.lang.Object) 
location: class java.util.ArrayList<Thing> 
      thing.add(otherThing); 
       ^
1 error 

這可能嗎?

感謝

+1

'otherThing'是如何聲明的? – 2013-04-23 03:39:48

回答

7

otherThing的類型必須爲Thing的。目前它的類型爲Object,這就是爲什麼它適用於第一種情況,但在第二種情況下失敗。

在第一個情況中,需要ArrayList<Object>Object類型的元素。由於otherThing也是類型Object,所以它的工作原理。

在第二種情況下,需要ArrayList<Thing>Thing類型的元素。因爲,你的otherThing的類型是Object仍,而它應該是類型Thing的,你得到這個錯誤。

0
ArrayList<Thing> thing = new ArrayList<Thing>(); 

爲此,您只能添加Thing類型的實例,而不允許這樣做,因爲它違反了Java通用準則。

ArrayList<Object> thing = new ArrayList<Object>(); 

因爲在這裏你指定的對象和作爲對象是超類,它會正常工作。

0

otherThing未聲明爲Thing而是Object

相關問題