1

My question is that if I have an array like

String [] varNames=new String[numOfVariables];
for(int i=0;i<numOfVariables;i++){
        varNames[i]=scan.next();

    }

and I want to make a new array of integers which will have a name of entry which is at varNames[1].

for example if at the place of varNames[1], "fish" is stored then I want to assign the name which is at varNames[1] to the new array of integers i am going to make.

Like

int [] verNames[i]=new int[20];

But I don't know how can I do that.....Any ideas would be really appreciated. Thanks.

BlackSwan
  • 73
  • 1
  • 7
  • I think he want the int array to be named "fish". Maybe you should use somethink like a `Map>` for that –  Dec 23 '14 at 09:24
  • I just want to use the name of that int array as "fish".... like int [] fish=new int[20]; – BlackSwan Dec 23 '14 at 09:24
  • 2
    You are looking for a `Map` – amit Dec 23 '14 at 09:24
  • Why you need it? And how you expect to use it? – talex Dec 23 '14 at 09:30
  • possible duplicate of [Is there away to generate Variables' names dynamically in Java?](http://stackoverflow.com/questions/1192534/is-there-away-to-generate-variables-names-dynamically-in-java) – talex Dec 23 '14 at 09:31

5 Answers5

6

You are looking for Map<String,T> - where T is your type of variable.

This is the "way to go", since java is not a dynamic binding language, and all variable names (and types) must be known at compile time.

amit
  • 175,853
  • 27
  • 231
  • 333
1

Java doesn't support dynamic variables, they must be declared in the source code (strictly typed).

You can work with maps to get something close to what you're trying to do, visit the Map API.

Maroun
  • 94,125
  • 30
  • 188
  • 241
1
int [] verNames[i]=new int[20];

No. That's not possible. Variable names should not be dynamic. They are strictly typed.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

You can not give variable names dynamically. Also you need to declare variable names even before compilation of the program.

However if you want you can do it like this to have multiple variable stored in collection.

Map<String, Integer> map = new HashMap<String, Integer>();
for(int i = 0; i < 2; i++)
{
  map.put("n1", i);
}
eatSleepCode
  • 4,427
  • 7
  • 44
  • 93
1

From your question:

int [] verNames[i]=new int[20];

This is not possible. You can't create the variables in run-time.

Ant's
  • 13,545
  • 27
  • 98
  • 148