sbnarra
sbnarra

Reputation: 584

Java variable value as new variable name

I was wondering if in Java there was any way to give a new variable a name which is the value of another variable. The below code is an non working example of what I'm trying to do.

int a = 0;
while(true){
    String (a) = "newValue";
    a = a + 1;
}

or

String b = "newVariableName";
int (b) = 1;

Thank for any help given.

Upvotes: 3

Views: 13564

Answers (6)

user1190541
user1190541

Reputation:

I dont think reflection will help because there is no way how to create new instance of Field. So something like

Map<String,Field> 

wont work. Use javascript instead :)

Upvotes: 0

Tim
Tim

Reputation: 1344

No this is not possible. It is possible to create a new object and add it to an array or some sort of list. Then you can reference the new object by the subscript. So a rough example could be:

Object[] a = new Object[30]; 

for(int i = 0; i < 30; i++)
{
a[i] = new Object();
}

and then you could use

a[some number].someFunction();

If you think about it, how can the compiler know what the value of a certain true variable is going to be, outside of the actual program run time? It is unlikely that you need to actually do what you want however.

Upvotes: 4

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

You cannot create dynamic variable names in Java. I would recommend placing these variables in a Map with a string as a key. The key can be whatever String you would like.

Upvotes: 0

Pointy
Pointy

Reputation: 413682

No, there's no way to do such a thing in Java. The closest you could do would be to create code at runtime and load a new class with fields made with dynamic names.

You might want to consider something simpler like a HashMap instance.

Upvotes: 0

Matti Virkkunen
Matti Virkkunen

Reputation: 65116

You can't do this. Use a Dictionary or a Map to store the values.

Upvotes: 0

SLaks
SLaks

Reputation: 887225

You're trying to make an array or a list or a dictionary.

Upvotes: 1

Related Questions