I am relatively new to Java. I wanted to create an arraylist of an outer class and for each index of the outer class of the arraylist I want an arraylist of inner classes.
public Outerclass{
//Code Here
public InnerClass{
//Code Here
}
}
//My attempt at setting up the arrays
public ArrayList <Outerclass> olist;
public ArrayList <InnerClass> ilist;
olist= new ArrayList<Outerclass>();
for (int i = 0; i < 3; i++) {
Outerclass c = new Outerclass ();
ilist = new ArrayList<InnerClass>();
for(int j = 0 ; j < 4; j++){
InnerClass e = new InnerClass();
ilist.add(e);
}
olist.add(c);
}
Will this work?
Here are the key lines of your code:
That won't work. You will get a compilation error.
Since
InnerClass
is an inner class, it needs to be instantiated in the context of an instance of its enclosing class (i.e.OuterClass
). Like this:The
c.new ...
form is called a qualified class instance creation expression; see JLS 15.9.Notes:
If the code that creates the inner class is in the context of an instance of the outer class (e.g. it is in an instance method of the outer class) then you don't need to qualify the
new
like that.If the
InnerClass
isstatic
this isn't necessary either. But thenInnerClass
is a nested class not an inner class ... according to the standard Java terminology.