Assigning variables with dynamic names in Java -


i'd assign set of variables in java follows:

int n1,n2,n3;  for(int i=1;i<4;i++) {     n<i> = 5; } 

how can achieve in java?

this not how things in java. there no dynamic variables in java. java variables have declared in source code (*). period.

depending on trying achieve, should use array, list or map; e.g.

int n[] = new int[3]; (int = 0; < 3; i++) {     n[i] = 5; }  list<integer> n = new arraylist<integer>(); (int = 1; < 4; i++) {     n.add(5); }  map<string, integer> n = new hashmap<string, integer>(); (int = 1; < 4; i++) {     n.put("n" + i, 5); } 

it possible use reflection dynamically refer to variables have been declared in source code. however, only works variables class members (i.e. static , instance fields). doesn't work local variables. see @fyr's "quick , dirty" example.

however doing kind of thing unnecessarily in java bad idea. inefficient, code more complicated, , since relying on runtime checking more fragile.

and not "variables dynamic names". better described dynamic access variables static names.


* - statement inaccurate. if use bcel or asm, can "declare" variables in bytecode file. don't it! way lies madness!


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

php - Cannot override Laravel Spark authentication with own implementation -

Qt QGraphicsScene is not accessable from QGraphicsView (on Qt 5.6.1) -