在Salesforce中列出

问题描述 投票:1回答:1

当我执行下面的代码说没有找到变量myList时,我收到一条错误消息。

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

    public static void main() {
        System.debug(myList);
    }
}
java list salesforce
1个回答
0
投票

您的代码存在一些问题:

  • 语法List<Integer> myList=new List<Integer>{1, 2, 3, 4, 5};不正确。您无法创建这样的列表。你应该使用一个实现List的类,这是一个接口,比如ArrayListLinkedList等。正确的语法就是List<Integer> myList=new ArrayList<Integer>();
  • 变量myList不是静态的,静态方法中不能加入非静态字段。

example of how to fix it中使用Arrays#asList查看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]
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.