R
R
reus2017-03-28 10:48:44
Java
reus, 2017-03-28 10:48:44

How to create a variable from an array?

In general, for example, we have some kind of array (ArrayList):

ArrayList<String> list = new ArrayList<String>();
list.add("x");
list.add("y");

How to create variables from the contents of an array? That is, something like this:
for(String i : list) {
this.i = "This is "+i;
}
System.out.println(x+" "+y);

for example, in python there is such a way to create variables (including from an array):
locals()['x']='Это х'
print x

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zakharov Alexander, 2017-03-28
@AlexZaharow

Your desire is very similar to using map. Those. you just need to convert list to map. You will even get a bonus in the form of using characters forbidden in ordinary life in the names of "variables".

Map<String, String> tables_sql = new HashMap<>();
for( String role : new String[]{"cv_administrators+!;", "cv_operators", "cv_translators"}){
        tables_sql.put(role, "This is role "+role);
}
// получение значения:
String val = tables_sql.get( "cv_administrators+!;" );  // This is role cv_administrators+!;

T
tyamur, 2017-03-29
@tyamur

Do you want to create variables on the fly? It's impossible.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question