Is there a more efficient way to create new variables in a for loop?

If you have an ArrayList (with a name alin this case), and you want to get the first five elements of the list as variables, you can do this:

    String x1 = al.get(0);
    String x2 = al.get(1);
    String x3 = al.get(2);
    String x4 = al.get(3);
    String x5 = al.get(4);

However, using a for loop, is there a way to do something like this:

for (int i = 1; i < 6; i++){
    String namer = "x" + i.toString();
    String [value of String 'namer'] = al.get(i-1);
}

Or is there a completely different method that is much more efficient?

+4
source share
5 answers

Dynamic metaprogramming in java is not possible. Depending on what you are trying to achieve, there will be different options.

5 , , . , , Java Collections Framework, " ":

List<String> nextFive = list.subList(5, 10);
+5

String 6 :

String[] str = new String[6];
for(int i=0; i<str.length; i++)
    a[i] = al.get(i);
+3

, ( , , ), , ,

,

Map variables = new HashMap();
for (int i = 1; i < 6; i++) {
    variables.put("x"+i, al.get(i-1));
}

,

variables.get("x1"); //or x2,x3,x4
+2

ArrayList , ?

int i = 0;
for (Object obj : al) {
    if (i > 5) { break; }
    results.append(obj); // append the first five elements to the result
}

, , , , get() - O (n). get() n! n .

+1

"", , ( ):

  • (String x1 = ...) *.java ( )
  • Java *.class
  • class-load *.class
+1

All Articles