Skip to content
Advertisement

How to return a list of strings in Java?

I want to return a list of strings when I call the method generateArrayList(2); It reminds me "Method does not exist or incorrect signature: void generateArrayList(Integer) from the type anon" Anyone help me, please! here is my class:

public class StringArrayTest {      
    public static List<String> generateArrayList(integer n){
        List<String> stringArray = new List<String>();
        for (integer i=0;i<n;i++){
            String str= 'Test'+String.valueOf(i);
            stringArray.add(str);
        }
        return stringArray;
    }
}

Advertisement

Answer

You have few compile time errors which needs to be corrected before it can work correctly.

  1. integer: It will either be an int or an Integer. Use ArrayList
  2. new List<String>: It’s an interface. You can’t instantiate an interface.
  3. 'Test': Single quotes is used for Character literal, for Strings use double quotes.
  4. Also, there’s no need of string.valueOf(i).

Below, I have corrected all these errors. It should work now.

public static List<String> generateArrayList(int n){
    List<String> stringArray = new ArrayList<>();
    for (int i=0;i<n;i++){
        String str= "Test" + i;
        stringArray.add(str);
    }
    return stringArray;
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement