arraylist of arraylists

I am trying to create an arraylists of arraylists in java. To print off the data in each array list I use this method:

void printAL(ArrayList arrlist)
{
     StringBuffer strbuf = new StringBuffer();
     for (int i = 0; i < arrlist.size(); i++) {
          String bla = (String)arrlist.get(i);
          strbuf.append(bla);
     }
     System.out.println(strbuf.toString());
}

then the code for adding data to the main arraylist is something like this:

ArrayList mainarrlist = new ArrayList();
while (condition) {
        /* Code for getting a single array list called arrlisttemp */
        printAL(arrlisttemp); // this works at this point
        mainarrlist.add(arrlisttemp);
        arrlisttemp.clear();
}

// then code to get and print the array lists back:
for (int i = 0; i < mainarrlist.size(); i++) {
     System.out.print(i+": ");
        printAL((ArrayList)mainarrlist.get(i)); // this doesnt work
}

Any idea as to why it doesn't work?
LVL 7
maUruAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
objectsConnect With a Mentor Commented:
You need to add a copy of the ArrayList each time:

ArrayList mainarrlist = new ArrayList();
while (condition) {
       /* Code for getting a single array list called arrlisttemp */
       printAL(arrlisttemp); // this works at this point
       mainarrlist.add(arrlisttemp.clone());
       arrlisttemp.;
}

Or alternatively create a new ArrayList for each loop:

ArrayList mainarrlist = new ArrayList();
while (condition) {
       ArrayList arrlisttemp = new ArrayList();
       /* Code for getting a single array list called arrlisttemp */
       printAL(arrlisttemp); // this works at this point
       mainarrlist.add(arrlisttemp);
}

0
 
yongsingCommented:
It's printing nothing because you clear the array after you add it into the main array:

mainarrlist.add(arrlisttemp);
arrlisttemp.clear(); // remove this line

So what you can do is to remove:

arrlisttemp.clear();
0
 
objectsCommented:
oops the first option should be:

ArrayList mainarrlist = new ArrayList();
while (condition) {
      /* Code for getting a single array list called arrlisttemp */
      printAL(arrlisttemp); // this works at this point
      mainarrlist.add(arrlisttemp.clone());
      arrlisttemp.clear();
}

Though I'd suggest the second option.

0
All Courses

From novice to tech pro — start learning today.