Reputation: 607
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
Reputation: 178253
Here's what your program does.
You have an ArrayList
of Foo
called fooList
. It can contain Foo
objects, but not other ArrayList
s.
The prepArrayLists
adds the contents of 20 empty ArrayList
s to fooList
. They're all empty, so nothing is added.
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 ArrayList
s 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 ArrayList
s in prepArrayLists
, but temp
will need to be declared as List<Foo>
.
Upvotes: 1
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