0

Today I wanted to use the java code below and it did not work of course. I know that in order to process the idea below I should create a basic array which should include all my String variables but... I am wondering is there an option to change my code and process the code without the mentioned basic array ?

ArrayList<String> array = new ArrayList<String>();

String variable1 = "text1";
String variable2 = "text2";
String variable3 = "text3";

for ( int i = 1; i <= 3; i++ ){
array.add(i, variable + i ); // error 
}

thank you in advance !

kendzikq
  • 45
  • 5

1 Answers1

0

This is the only reasonable way, if we ignore fact that your array is already a collection.

ArrayList<String> array = new ArrayList<String>();

String[] variables=new String[3];
variables[0] = "text1";
variables[1] = "text2";
variables[2] = "text3";

for ( int i = 0; i < 3; i++ ){
    array.add(variables[i]); // error 
}
Antoniossss
  • 31,590
  • 6
  • 57
  • 99