2013-04-23 37 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

相关问题