-4

I currently have an array of arrays and that would work fantastic, except I just realized that I don't know the length of all of the arrays that I need. So I have to switch to ArrayList. I'm used to having an array of arrays and I know how to iterate through them. How do you do the same thing with ArrayLists?

The following works... until I need to change line size through my iterations.

Person[][] nameList = new Person[yearsBack][lines];
for (int i=0; i<yearsBack; i++) {
    for (int j=0; j<lines; j++) {
        nameList[i][j] = new Person(name, gender, rank);
dimo414
  • 47,227
  • 18
  • 148
  • 244
Gil
  • 85
  • 8
  • 1
    `ArrayList>`? – Evan Knowles Mar 13 '15 at 05:36
  • Have you seen the Java tutorials on using [`List`s](http://docs.oracle.com/javase/tutorial/collections/interfaces/list.html) and [generics](http://docs.oracle.com/javase/tutorial/java/generics/)? – dimo414 Mar 13 '15 at 05:42
  • You might be interested in this post http://stackoverflow.com/questions/4401850/how-to-create-a-multidimensional-arraylist-in-java – sreeAravinth Mar 13 '15 at 05:45

3 Answers3

1

This should do it:

List<List<Object>> listOfLists = new ArrayList<>();

To loop through:

for(List<Object> list : listOfLists){
    for(Object obj : list){
        //do stuff
    }
}
Brandon
  • 317
  • 1
  • 10
  • How do you access specific points in the ArrayList like you can with Arrays? And by that I mean, the way you can access them in nested for loops with list[i][j]? – Gil Mar 13 '15 at 05:38
  • Use `list.get(i)` where `i` is an index – Brandon Mar 13 '15 at 05:39
0

ArrayList < Objects > can hold the Arraylist Objects and thus you can have the array of arraylists.

kondu
  • 410
  • 3
  • 11
0
import java.util.ArrayList;

public class Test {

    public static void main(String[] args) {
        ArrayList<Object> mainAl = new ArrayList<Object>();
        ArrayList<Integer> al1 = new ArrayList<Integer>();
        ArrayList<String> al2 = new ArrayList<String>();
        ArrayList<Double> al3 = new ArrayList<Double>();
        ArrayList<ArrayList<Object>> al4 = new ArrayList<ArrayList<Object>>();
        al1.add(1);
        al1.add(2);
        al1.add(3);
        al1.add(4);
        al2.add("Hello");
        al2.add("how");
        al2.add("are");
        al2.add("you");
        al3.add(100.12);
        al3.add(200.34);
        al3.add(300.43);
        al3.add(400.56);
        mainAl.add(al1);
        mainAl.add(al2);
        mainAl.add(al3);
        for (Object obj : mainAl) {
            System.out.println(obj);
        }
        al4.add(mainAl);
        for (Object obj : al4) {
            System.out.println(obj);
        }
    }
}

I hope this example is helpful for you.

raghavanm
  • 13
  • 6