Accessing ArrayList of an ArrayList

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sid0404
    New Member
    • Jul 2008
    • 16

    Accessing ArrayList of an ArrayList

    Hi

    How do I print elements of an ArrayList of an ArrayList, I think it has to be something similar to a 2 D array, but with a difference, my child arraylist has different number of elements say I have 3 child lists and they have 2, 5, 4 elements when I add them to the parent arrayList, but the number of elements in each child list can vary from time to time, can any one suggest a modular approach towards it ?

    Clarification appreciated.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Why not use the for-each loop? In the next example I assume that your inner
    Lists contain Strings; have a look:

    Code:
    ArrayList<ArrayList<String>> outer= ...; // your outer list
    for (List<String> inner : outer) // loop over outer list
       for(String str : inner) // loop over inner list
          // do something with str
    Of course you can also use an old fashioned for loop:

    Code:
    ArrayList<ArrayList<String>> outer= ...; // your outer list
    for (int i= 0, n= outer.size(); i < n; i++) { // loop over outer list
       List<String> inner= outer.get(i);
       for (j= 0, m= inner.size(); j < m; j++) {
          String str= inner.get(j);
          // do something with str
       }
    }
    Or you can user Iterators (left to the reader for an exercise)

    kind regards,

    Jos

    Comment

    Working...