This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Dynamically creating ArrayList inside a iterator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Dynamically creating ArrayList inside a iterator" Watch "Dynamically creating ArrayList inside a iterator" New topic

Dynamically creating ArrayList inside a iterator

satheesh krishnaswamy
Ranch Hand

Joined: Mar 17, 2004
Posts: 137

My requirement is this:-

I need to create "n" number of ArrayLists inside for loop dynamically n is based on a field value, which will also change.

Something like this:-
In the first iteration

for(int i=0;i<20;i++)
ArrayList firstIteration = new ArrayList();

and in the second iteration it should be like this...

for(int i=0;i<20;i++)

ArrayList SecondIteration = new ArrayList();

Please let me know How do I do this?

Thanks in advance,
Norm Radder
Ranch Hand

Joined: Aug 10, 2005
Posts: 696
Looks like you should use an array of ArrayLists. Create a new ArrayList and add it as the next element in the array at each iteration thru the for loop.
Mark Vedder
Ranch Hand

Joined: Dec 17, 2003
Posts: 624

Or a collection, like a List. So you'd have a list of lists.
Adinath Shirsath
Ranch Hand

Joined: Dec 04, 2007
Posts: 35
or you can use HashMap also

HashMap iterationmap = new HashMap();
for(int i=0;i<20;i++)

ArrayList iterationList = new ArrayList();
iterationmap.put("Iteration" + i , iterationList);

then you can get lists from map based on iteration no as key
I agree. Here's the link:
subject: Dynamically creating ArrayList inside a iterator
It's not a secret anymore!