I want to dynamically create ArrayLists inside a loop like:
for (i = 0; i < 3; i++) {
List<myItems> d(i) = new ArrayList<myItems>();
}
All I want to do is create 3 such lists inside a loop. Can I do that?
No: variable names are merely a convenience for the programmer and are not kept track of after your code is compiled, so that kind of "dynamic variable naming" is not allowed. You will have to find another way to keep track of your lists, such as a Map<String, List<Item>> that maps string identifiers to lists:
Map<String, List<Item>> map = new HashMap<String, List<Item>>()
map.put("d1", new ArrayList<Item>());
...
To then access the list corresponding to "d1", for example you can just use map.get("d1").
If you do this:
for(i=0;i<3;i++){
List<myItems> d = new ArrayList<myItems>();
}
You will create a new array list three times. But each time you will store it to a newly created reference d and once you leave the scope of the for loop, that reference will vanish.
What you may be looking for is this:
List<List<myItems>> d = new ArrayList<List<myItems)>();
for(i=0;i<3;i++){
d.add(new ArrayList<myItems>());
}
This creates a nested list:
someListOfListsOfMyItems
subListOfMyItems
someMyItem
anotherMyItem
subListOfMyItems
someOtherMyItem
anotherOtherMyItem
subListOfMyItems
yetSomeOtherMyItem
yetAnotherMyItem
Each sublist can be accessed like so:
d.get(indexOfSublist);
d.get(idx).add(aNewItem);, where idx is the index of the sublist you're adding to. @ohlala
newtwice) but it's not accomplishing anything. You're just creating a new List every time through the loop without using it. What exactly are you trying to accomplish?