Hi,
I have an ArrayList of ArrayLists. I want to extract all the lists,
but I dont know how many ArrayLists will be in the ArrayList.
I know I can do it if i know how many lists are there using the
ArrayList get() method.
this is how i'm doing it
List<String> list1 = new ArrayList<String>();
list1 = res.get(0);
List<String> list1 = new ArrayList<String>();
list2 = res.get(1);
List<String> list1 = new ArrayList<String>();
list3 = res.get(2);
But if theres only two lists in the list i get a NullPointerException
Is there any way i can loop through the list and extract the lists
thanks
Michael Rauscher - 08 Feb 2007 23:28 GMT
Damo schrieb:
> Hi,
> I have an ArrayList of ArrayLists. I want to extract all the lists,
[quoted text clipped - 6 lines]
> List<String> list1 = new ArrayList<String>();
> list1 = res.get(0);
The first line is... nonsense. You don't need to allocate an ArrayList
at this point since you get a List<String>-object from res.get(0);
> Is there any way i can loop through the list and extract the lists
Several. I assume that res is declared something like
List<List<String>> res;
1. for ( int i = 0, n = res.size(); i < n; i++ )
List<String> l = res.get(i);
2. Iterator<List<String>> it = res.iterator();
while ( it.hasNext() )
List<String> l = it.next();
3. for ( List<String> l : res )
...
Bye
Michael
Oliver Wong - 08 Feb 2007 23:32 GMT
> Hi,
> I have an ArrayList of ArrayLists. I want to extract all the lists,
[quoted text clipped - 14 lines]
>
> Is there any way i can loop through the list and extract the lists
Check the javadocs for ArrayList. There's a method to get its size or
length, which will be the number of inner lists contained by the outer list.
- Oliver
Damo - 08 Feb 2007 23:52 GMT
List<List<String>> res;
1. for ( int i = 0, n = res.size(); i < n; i++ )
List<String> l = res.get(i);
2. Iterator<List<String>> it = res.iterator();
while ( it.hasNext() )
List<String> l = it.next();
3. for ( List<String> l : res )
But if I use those ways you mentioned , each time around the loop l
will contain a different list, i wont be using the lists in the loop.
so at the end of the loop i will only have one list, ie the last one.
Lew - 09 Feb 2007 01:02 GMT
It helps other readers if you distinguish who wrote what.
Michael Rauscher wrote:
> List<List<String>> res;
>
[quoted text clipped - 10 lines]
> will contain a different list, i wont be using the lists in the loop.
> so at the end of the loop i will only have one list, ie the last one.
That has nothing to do with using Michael's suggestion but with what you do
with the result each time through the loop. The assumption in Michael's
suggestion is that you will
do something useful with each list
during each iteration.
You cannot expect newsgroup answers to write out every line of code. You
should impute the missing parts. If you "won't be using the lists in the loop"
then you only have yourself, not Michael, to blame.
- Lew