简体   繁体   中英

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.


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.

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(){
    }   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM