[英]Creating an array list of objects
I have two classes A and B. B extends A. Now, in B, can I create an array list of objects of A. 我有两个类A和B。B扩展了A。现在,可以在B中创建A的对象的数组列表。
public class A {
// class fields
// class methods
}
import java.util.*;
public class B extends A {
List<Object> listname=new ArrayList<Object>();
A obj=new A();
listname.add(obj);
}
Can I create an array list of objects at all ? 我可以完全创建对象的数组列表吗? By the way, above code gives error !
顺便说一句,上面的代码给出了错误!
Yes, I see no reason you cannot create an ArrayList of an object A. 是的,我认为没有理由不能创建对象A的ArrayList。
But you can't do it the way you are doing it, you must do it in a method. 但是您不能以自己的方式进行操作,必须以一种方法来执行。 You're trying to do it in the field declarations.
您正在尝试在字段声明中执行此操作。
Try maybe adding it in the constructor? 尝试将其添加到构造函数中?
So something like 所以像
public B() {
A obj=new A();
listname.add(obj);
}
Or maybe I just don't understand your question and I'm completely wrong. 也许我只是不明白您的问题,而我完全错了。
The error is because you have code outside a method. 该错误是因为您在方法外部有代码。 Try this:
尝试这个:
public class B extends A {
private static List<Object> listname = new ArrayList<Object>();
public static void main(String[] args) {
A obj = new A();
listname.add(obj);
}
}
Use an instance initializer if you want to add items to your list outside of any method: 如果要通过任何方法将项目添加到列表中,请使用实例初始化器:
public class B extends A{
private List<A> listOfA = new ArrayList<A>();
{
listOfA.add(new A());
}
public B(){
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.