如何从各种类访问公共静态ArrayList?

Vij*_*der 3 java static public arraylist

假设我有一堂课

    public class c1 {
        public static ArrayList<String> list = new ArrayList<String>();

        public c1() {
            for (int i = 0; i < 5; i++) {   //The size of the ArrayList is now 5
                list.add("a");
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是如果我在另一个类中访问相同的ArrayList,我将得到一个SIZE = 0的列表.

     public class c2 {
         public c2() {
             System.out.println("c1.list.size() = " + c1.list.size()); //Prints 0
         }
     }
Run Code Online (Sandbox Code Playgroud)

为什么会这样呢?如果变量是静态的,那么为什么要为类c2生成新的列表?如果我在另一个类中访问它,如何确保获得相同的ArrayList?

/ ****修改后的代码******** /

     public class c1 {
        public static ArrayList<String> list = new ArrayList<String>();

        public static void AddToList(String str) {       //This method is called to populate the list 
           list.add(str);
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是如果我在另一个类中访问相同的ArrayList,我将获得一个SIZE = 0的列表,而不管我调用AddToList方法的次数.

     public class c2 {
         public c2() {
             System.out.println("c1.list.size() = " + c1.list.size()); //Prints 0
         }
     }
Run Code Online (Sandbox Code Playgroud)

当我在另一个类中使用ArrayList时,如何确保出现相同的更改?

Lui*_*oza 7

在你的代码中,你应该调用c1构造函数来填充ArrayList.所以你需要:

public c2() {
    new c1();
    System.out.println("c1.list.size() = " + c1.list.size()); //Prints 0
}
Run Code Online (Sandbox Code Playgroud)

但这并不好.最好的方法是使用类中的static块代码进行静态初始化c1:

public class c1 {
    public static ArrayList<String> list = new ArrayList<String>();

    static {
        for (int i = 0; i < 5; i++) {   //The size of the ArrayList is now 5
            list.add("a");
        }
    }

    public c1() {

    }
}
Run Code Online (Sandbox Code Playgroud)

作为"编程到界面"是什么意思的推荐,最好将变量声明为List<String>并创建实例ArrayList:

public static List<String> list = new ArrayList<String>();
Run Code Online (Sandbox Code Playgroud)

另一个建议,使用static方法来访问此变量而不是将其公开:

private static List<String> list = new ArrayList<String>();

public static List<String> getList() {
    return list;
}
Run Code Online (Sandbox Code Playgroud)