且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Singleton类初始化/访问ArrayList

更新时间:2023-08-21 16:14:58

以下是创建单身类的方法:

Here is how to create your singleton class :

    public class YourSingleton  {  

        private static YourSingleton mInstance;
        private ArrayList<String> list = null;

        public static YourSingleton getInstance() {
            if(mInstance == null)
                mInstance = new YourSingleton();

            return mInstance;
        }

        private YourSingleton() {
          list = new ArrayList<String>();
        }
        // retrieve array from anywhere
        public ArrayList<String> getArray() {
         return this.list;
        }
        //Add element to array
        public void addToArray(String value) {
         list.add(value);
        }
}

您需要调用arrayList的任何地方:

Anywhere you need to call your arrayList just do :

YourSingleton.getInstance().getArray(); 

要向阵列使用添加元素:

To add elements to array use :

 YourSingleton.getInstance().addToArray("first value"); 

YourSingleton.getInstance().getArray().add("any value");