Reputation: 1
I need to create 50 arraylists
but rather than having to initialise them all individually. Is there a way in JAVA that I can do this dynamically??
i.e.
pseudo code:
for int i=1; i<51; i++
List<String> Counti = new ArrayList<String>();
So that in the loop it goes through and create 50 arraylists all called Count1, Count2, Count3
etc up until Count50
.
I've tried creating a string and then naming the list by the string but it doesnt seem to recognise that teh name is a variable.
e.g.
for int i=1; i<51; i++
String Name="Count "+i
List<String> Name = new ArrayList<String>();
Instead it just creates a list called "Name"
Upvotes: 0
Views: 133
Reputation: 5235
You need a List
of ArrayList
.
List<List<String>> lists = new ArrayList<>();
for (int i = 0; i < 50; i++){
lists.add(new ArrayList<String>());
}
Upvotes: 1
Reputation: 16833
You should store them in a List
and not create 50 variables
List<List<String>> lists = new ArrayList<ArrayList<String>>();
for (int i = 0; i < 50; i++)
{
lists.add(new ArrayList<String>());
}
Upvotes: 1
Reputation: 12523
one another possible solution is to use a HashMap
like this to name the ArrayLists
:
Map<String, ArrayList<String>> mAllArrayListsByName = new HashMap<String, ArrayList<String>>();
for (int i = 0 ; i < 50 ; i++){
mAllArrayListsByName.put("List"+String.valueOf(i), new ArrayList<String>());
}
ArrayList<String> lMyArrayList = mAllArrayListsByName.get("List0"); // get List 0
Upvotes: 0
Reputation: 16641
You can do this with reflection, but this is a pretty bad idea. What you probably want to do is create an arraylist of arraylists.
ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();
for (int i = 0; i < 50; i++)
listOfLists.add(new ArrayList<String>());
Upvotes: 3