1

I have an ArrayList object to which I want to dynamically add ArrayLists.

However, since the compiler doesn't know what objects are going to be inside the outer ArrayList before the loop to add them runs, I can't use the inner ArrayLists as I normally would.

My code looks somewhat like this:

ArrayList list = new ArrayList();

 for(int i=8;i>0;i--)
 {
     list.add(i, new ArrayList());
 }

 for(int i=8;i>0;i--)
 {         
    tileRows.get(i).add( //add other stuff );
 }

How can I tell the compiler that the items in list are going to be of ArrayList type?

Bear in mind that I'm completely new to Java. If this is a stupid question I apologise.

Obversity
  • 567
  • 2
  • 9
  • 21

5 Answers5

2

You can declare a List<Whatever>, and Whatever can be another interface/class that supports generics, like List<String>, so putting all this together you can declare a List<List<String>> and the compiler will be happy. Based on your code above:

List<List<String>> tileRows= new ArrayList<List<String>>();
for(int i=8;i>0;i--) {
    list.add(i, new ArrayList<String>());
}

for(int i=8;i>0;i--) {
    //here the compiler knows tileRows.get(i) is a List<String>
    tileRows.get(i).add("foo");
    //uncomment the below line and you will get a compiler error
    //tileRows.get(i).add(new Object());
}

Remember to always program to an interface, not to a direct class implementation.

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
2

You do it the same way you do with any other type of Object. You cast it:

((ArrayList)tileRows.get(i)).add( //add other stuff );

Or better yet, you use generics so you don't have to do that cast:

//this tells the compiler that your ArrayList will contain ArrayLists
ArrayList<ArrayList<Whatever>> list = new ArrayList()<>;
//now the compiler knows the get() function returns an ArrayList, so you don't have to cast it
tileRows.get(i).add( //add other stuff );
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
2

This is Java Generic, and the correct use is some like this:

 ArrayList<ArrayList> list = new ArrayList<ArrayList>();

 for(int i=8;i>0;i--)
 {
     list.add(i, new ArrayList());
 }

 for(int i=8;i>0;i--)
 {         
    tileRows.get(i).add( //add other stuff );
 }
wrivas
  • 509
  • 6
  • 12
1
List<List<String>> list = new ArrayList<>();
Kakarot
  • 4,252
  • 2
  • 16
  • 18
1
List<ArrayList<Object>> list = new ArrayList<>();

in Java 7

Philipp Sander
  • 10,139
  • 6
  • 45
  • 78