【问题标题】:ArrayList initialized/accessed using Singleton class使用 Singleton 类初始化/访问的 ArrayList
【发布时间】:2016-10-20 10:56:31
【问题描述】:

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

我想知道从 Singleton 类初始化我的 ArrayList 的确切过程。
这些数据将用于其他一些活动。

有人可以帮忙了解一下单例类吗?

【问题讨论】:

  • 请添加一些代码和进一步的解释,以帮助我们理解问题。
  • 你做了哪些努力
  • 希望你能按时交作业!

标签: java android arraylist singleton


【解决方案1】:

这里是如何创建你的单例类:

    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 就可以了:

YourSingleton.getInstance().getArray(); 

要将元素添加到数组使用:

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

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

【讨论】:

  • 谢谢@Anto.. 还有一件事是我可以在同一个单例类中使用多个数组列表
  • 是的,你可以,并创建不同的方法来调用正确的数组。在这个例子中,你有 getArray()。您可以创建 getFirstArray()、getSecondArray() 等...只需在类声明中添加其他数组并在构造函数中初始化它们,就像我为“列表”所做的那样
  • 有一个想法.. 非常好心@Anto Lemme 结帐并告诉你
  • 如何从单例类中设置 list 中的数据
  • 编辑了我的帖子,你需要创建一个会影响数组的方法
【解决方案2】:

请查看以下维基百科文章:

https://en.wikipedia.org/wiki/Singleton_pattern

但请记住,单例是“全局状态”,会使您的源代码更难测试。很多人说:“单身是邪恶的”

【讨论】:

    【解决方案3】:

    我认为你需要这样的东西。

    public class SingletonClass {
    
        private static ArrayList<String> strArray;
        private static SingletonClass singleton;
    
        private SingletonClass(){}
    
        public static synchronized SingletonClass getConnectionInstance(ArrayList<String> strArray){        
            if (singleton == null) {
                 singleton = new SingletonClass();
            }
            this.strArray = strArray;
            return singleton;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多