-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);
3
  • 1
    ArrayList<ArrayList<Object>>? Commented Mar 13, 2015 at 5:36
  • Have you seen the Java tutorials on using Lists and generics? Commented Mar 13, 2015 at 5:42
  • You might be interested in this post stackoverflow.com/questions/4401850/… Commented Mar 13, 2015 at 5:45

3 Answers 3

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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]?
Use list.get(i) where i is an index
0

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.