How to concatenate variable names in Java

2

I have a question. I want to generate a total of variables, from a for , so I do not have to write all of them, but I can not concatenate the variable names.

I'm trying this way:

for(int i = 0; i < 4; i++){
     String nome + i = null;
}

I would like a return of:

nome0 = null;
nome1 = null;
nome2 = null;
nome3 = null;
  • You can create multiple variables with a structure of repetition?

  • Why does not it work that way?

asked by anonymous 15.10.2018 / 16:51

1 answer

4

This is not possible. There are no dynamic variables in Java. Java variables need to be declared in the source code.

The closest result you can get and using ArrayList , String[] or Map .

How to:

List<String> nomes = new ArrayList();
for(int i = 0; i < 4; i++){
    nomes.add(null);
}

or:

int tamanho = 4;

String[] nomes= new String[tamanho];

for(int i = 0; i < tamanho; i++){
    nomes[i] = null;
}

or:

Map<String, String> nomes = new HashMap<String, String>();
for (int i = 1; i < 4; i++) {
    details.put("nome" + i, null);
}

You can use reflection to dynamically reference variables that have been declared in the source code. However, this only works for variables that are class members (that is, static and instance fields). It does not work for local variables.

However, doing this kind of thing unnecessarily in Java is a bad idea. It is inefficient, the code is more complicated, and as you are relying on run-time verification, it is more fragile.

And this is not "variables with dynamic names". It is best described dynamic access to variables with static names.

    
15.10.2018 / 16:58