Sometowngeek
Sometowngeek

Reputation: 607

How to access or add the ArrayList inside of another ArrayList?

I'm having trouble with accessing an ArrayList inside of another ArrayList. Like so:

    public class Bar{
        private static ArrayList<Foo> fooList = new ArrayList<Foo>();

        public static void main(String[] args){
            prepArrayLists();

            // This is what's not working (the next two lines)
            ArrayList<Foo> temp = fooParent.get(0);
            temp.add(new Foo(23, "Cows", true);
        }

        private static void prepArrayLists(){
            for (int x = 0; x < 20; x++){
                fooList.addAll(new ArrayList<Foo>());
            }
        }
    }

The compiler wouldn't let me do this. What I am trying to do is put an ArrayList of components (Foo) into another ArrayList, where I can sort it for other purposes.

I would like to stick with ArrayList of ArrayLists because I'm trying to see how this works. Any help would be appreciated :)

Upvotes: 0

Views: 227

Answers (2)

rgettman
rgettman

Reputation: 178253

Here's what your program does.

  1. You have an ArrayList of Foo called fooList. It can contain Foo objects, but not other ArrayLists.

  2. The prepArrayLists adds the contents of 20 empty ArrayLists to fooList. They're all empty, so nothing is added.

  3. You are attempting to get the first Foo out of fooList, and there isn't one. This fails with a compiler error, because you can't assign a Foo to an ArrayList<Foo>.

To have an ArrayList of ArrayLists of Foo, you need fooList to be an ArrayList<ArrayList<Foo>>, not an ArrayList<Foo>. You'll need to change the addAll line in prepArrayLists to add, so you can add each ArrayList to fooList. That will allow you to compile your code to get the first ArrayList and add a new Foo to it.

You may want to have fooList declared as follows, to follow the "code to the interface" guidelines.

private static List<List<Foo>> fooList = new ArrayList<List<Foo>>();

You can still add ArrayLists in prepArrayLists, but temp will need to be declared as List<Foo>.

Upvotes: 1

David
David

Reputation: 3113

You've declared fooList as an ArrayList<Foo>, that is, a list of Foo objects. You didn't post the compiler error message, but it's probably (correctly) telling you that a Foo cannot be converted to an ArrayList<Foo>.

If you want it to be a list of lists, you should declare it as an ArrayList<ArrayList<Foo>>, or possibly ArrayList<List<Foo>>, or maybe even ArrayList<Collection<Foo>>.

Upvotes: 0

Related Questions