Java-自定义类ArrayList没有add方法

Java-自定义类ArrayList没有add方法,java,Java,自定义类的ArrayList没有.add()方法: 我可以定义对象的ArrayList: ArrayList<Object> thing = new ArrayList<Object>(); thing.add(otherThing); // works ArrayList thing=new ArrayList(); 事物。添加(其他事物);//作品 但是,当我定义自定义类的列表时: ArrayList<Thing> thing = new Arra

自定义类的ArrayList没有.add()方法:

我可以定义对象的ArrayList:

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


thing.add(otherThing); // works
ArrayList thing=new ArrayList();
事物。添加(其他事物);//作品
但是,当我定义自定义类的列表时:

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
ArrayList thing=new ArrayList();
事物。添加(其他事物);//错误
Canvas.java:33:找不到符号
符号:方法添加(java.lang.Object)
位置:类java.util.ArrayList
事物。添加(其他事物);
^
1错误
这可能吗


谢谢

您的
其他物品
必须是
物品
的类型。目前它的类型是
对象
,这就是为什么它在第一种情况下有效,但在第二种情况下失败的原因

在第一种情况下,
ArrayList
采用
对象类型的元素。因为
otherThing
也是
Object
类型,所以它可以工作

在第二种情况下,
ArrayList
接受类型为
Thing
的元素。由于您的
otherThing
仍然是
对象的类型,而它应该是
Thing
的类型,因此您会得到该错误。

ArrayList Thing=new arrarylist();
ArrayList<Thing> thing = new ArrayList<Thing>(); 
为此,您只能添加Thing的类型/实例,但不允许添加,因为它违反了Java通用准则

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

在这里,您指定的是对象,而对象是超类,它可以正常工作。

其他事物
不是声明为
事物
,而是一个
对象

如何声明
其他事物