In programming language variable names is used to refers a stored value
in computer memory. So a variable name can be considered as a key
to access the value
stored in computer memory. The standard data structure Map
have the similar key
value structure. So we can user Map
here - "boom" as a key and new ArrayList<String>()
as an value.
Suppose you have all the names (that is boom, pow, bang) in the nameList
-
ArrayList nameList = new ArrayList(){{
add("boom");
add("pow");
add("bang");
}};
Now you want to create 3 ArrayList
of Stirng
by the name given in nameList
. So you put them in a Map<String, List<String>
like this -
Map<String, List<String> > vars = new HashMap<String, List<String>>();
for(int i=0; i<nameList.size(); i++){
String key = nameList.get(i);
List<String> value = new ArrayList<String>();
vars.put(key, value);
}
The complete cod can be -
import java.util.*;
public class ArrayListFromNameList {
public static void main(String[] args){
List<String> nameList = new ArrayList<String>(){{
add("boom");
add("pow");
add("bang");
}};
Map<String, List<String> > vars = new HashMap<String, List<String>>();
for(int i=0; i<nameList.size(); i++){
String key = nameList.get(i);
List<String> value = new ArrayList<String>();
vars.put(key, value);
}
}
/* Use the Map vars like this -
* vars.get("boom") --> will reuturns you an ArrayList<String>();
* similarly vars.get("pow") --> will returns you an ArrayList<String>();
*/
}