List in Salesforce

I am getting an error message when I am executing the below code saying that variable myList is not found.

public class ListExample {
    List<Integer> myList=new List<Integer>{1, 2, 3, 4, 5};

    public static void main() {
        System.debug(myList);
    }
}

1 answer

  • answered 2019-04-21 10:15 lealceldeiro

    There are some problems with your code:

    • The syntax List<Integer> myList=new List<Integer>{1, 2, 3, 4, 5}; is incorrect. You cannot create a list like that. You should use one of the classes that implement List which is an interface, such as ArrayList, LinkedList, etc. A correct syntax would be, for instance, List<Integer> myList=new ArrayList<Integer>();.

    • Variable myList is not static and non-static fields cannot be acceded inside static methods.

    See an example of how to fix it using Arrays#asList inside a Static Initialization Blocks:

    public class ListExample {
        static List<Integer> myList;
        static {
            myList= Arrays.asList(1, 2, 3, 4, 5);
    
            // this would work too
            // myList = new ArrayList<>();
            // for (int i = 1; i < 6; i++) {
            //     myList.add(i);
            // }
        }
        public static void main(String[] args) {
            System.out.println(myList);         // [1, 2, 3, 4, 5]
        }
    }