簡體   English   中英

如何從各種類訪問公共靜態ArrayList?

[英]How to access a public static ArrayList from various classes?

假設我有一堂課

    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");
            }
        }
    }

但是如果我在另一個類中訪問相同的ArrayList,我將獲得一個SIZE = 0的列表。

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

為什么會這樣呢? 如果變量是靜態的,那么為什么要為類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);
        }
    }

但是如果我在另一個類中訪問相同的ArrayList,我將獲得一個SIZE = 0的列表,而不管我調用AddToList方法的次數。

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

當我在另一個類中使用ArrayList時,如何確保出現相同的更改?

在你的代碼中,你應該調用c1構造函數來填充ArrayList 所以你需要:

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

但這並不好。 最好的方法是使用c1類中的static塊代碼進行靜態初始化:

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() {

    }
}

作為“編程到界面”是什么意思的推薦 ,最好將變量聲明為List<String>並將實例創建為ArrayList

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

另一個建議是,使用static方法來訪問此變量而不是將其公開:

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

public static List<String> getList() {
    return list;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM