This is not possible. There are no dynamic variables in Java. Java variables need to be declared in source code.
The closest result you can achieve and using ArrayList
, String[]
or a Map
.
Like:
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);
}
It is possible to use the reflection to dynamically reference variables that have been declared in the source code. However, this only works for variables that are class members (this 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 the run-time check, it is more fragile.
And this is not "variables with dynamic names". Dynamic access to variables with static names is best described.
Why don’t you use the
string[]
? Even more that will work with a structureFor
, better code using Arrays...– Victor Laio
@Victorlaio is that the intention, is not to create an array for the values, but several variables with different names, I put in question only an example of use.
– Gabriel Gonçalves
If you are working with fields of a class, it is possible to do this with the use of reflection and getDeclaredField(). But depending on the use case, it would be better to think about using some data structure, as suggested (array, or map).
– Leonardo Lima
Arrays, lists and
Map
They were created for it. But if for some reason you don’t want or can’t use them, then I suspect you don’t know exactly what you want to do or why. See more about this at XY problem.– Victor Stafusa
I intended to make a comment, but my score does not allow... The user’s answer is correct, it is not possible to do this in Java. There is probably a better data structure for what you want. If you have any questions regarding a specific case you can post another question... Good luck!
– Tomaz Fernandes
@Victorstafusa I have knowledge of these structures, I just wanted to know if it was possible to create in this way
– Gabriel Gonçalves