首页 > 解决方案 > Salesforce 中的列表

问题描述

当我执行以下代码时,我收到一条错误消息,提示myList找不到变量。

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

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

标签: javalistsalesforce

解决方案


您的代码存在一些问题:

  • 语法 List<Integer> myList=new List<Integer>{1, 2, 3, 4, 5};正确。_ 您不能创建这样的列表。您应该使用实现List接口的类之一,例如ArrayList,LinkedList等。例如,正确的语法应该是List<Integer> myList=new ArrayList<Integer>();.

  • 变量myList不是静态的,并且不能在静态方法中加入非静态字段。

请参阅如何使用静态初始化块Arrays#asList内部修复它的示例:

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]
    }
}

推荐阅读