使用Singleton类初始化/访问ArrayList [英] ArrayList initialized/accessed using Singleton class

查看:125
本文介绍了使用Singleton类初始化/访问ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用了一个ArrayList。

I am using an ArrayList in my application.

我想知道从Singleton类初始化ArrayList的确切过程。

数据将用于其他一些活动。

I would like to know the exact procedure to initialize my ArrayList from a Singleton class.
The data will be used in some other Activities.

任何人都可以帮助了解Singleton类吗?

Can anybody help to know about Singleton class?

推荐答案

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

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

这篇关于使用Singleton类初始化/访问ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆