Simple Apex class to return a list of strings
You can't instantiate a List
like that using an integer. You don't need to explicitly specify how much items are going into the list when it is created. Instead, just remove the integer:
//Instantiate the list
String[] myArray = new List<String>();
You're logic in your loop seems to be incorrect as well. Specifically, myArray
's size will always be 0 when you instantiate it. Change your loop logic to:
for(Integer i=0;i<length;i++) {
// code
}
You want to generate a List of strings based on the i
variable. You will want to change your internal logic to:
//Populate the array
myArray.add('Test ' + i);
// Write value to the debug log
System.debug(myArray[i]);
Finally, you want to return that Array. You need to change your method so the return type is no longer void
by changing its signature:
public static String[] generateStringArray(Integer length)
then it is just a matter of return
ing that array at the end of your method:
return myArray;
This would bring it all together as:
public class StringArrayTest {
//Public Method
public static String[] generateStringArray(Integer length) {
//Instantiate the list
String[] myArray = new List<String>();
//Iterate throught the list
for(Integer i=0;i<length;i++) {
//Populate the array
myArray.add('Test ' + i);
// Write value to the debug log
System.debug(myArray[i]);
} //end loop
return myArray;
}//end method
}// end class
Some more info on Arrays and Lists, Loops, and Class methods for future reference.
Problem is on the following line
String[] myArray = new List<String>(length);
Lists in Apex do not have constructor for creating lists of predefined length (see doc). This should solve the problem:
String[] myArray = new List<String>();
P.S. to satisfy your requirements, you will also have to change for-loop condition like this:
for(Integer i=0;i<length;i++) {
Here's my shot at it:
public class StringArrayTest {
//Public Method
public static List<String> generateStringArray(Integer length) {
//Instantiate the list
List<String> myArray = new List<String>();
//Iterate throught the list
for(Integer i=0;i<length;i++) {
//Populate the array
myArray.add('Test ' + i);
// Write value to the debug log
System.debug(myArray[i]);
} //end loop
return myArray;
}//end method
}// end class