【问题标题】:How to access a public static ArrayList from various classes?如何从各种类访问公共静态 ArrayList?
【发布时间】:2013-03-21 17:48:27
【问题描述】:

假设我有一堂课

    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

标签: java static arraylist public


【解决方案1】:

在您的代码中,您应该调用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() {

    }
}

根据What does it mean to "program to an interface"? 的建议,最好将变量声明为List&lt;String&gt;,并将实例创建为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;
}

【讨论】:

  • 感谢您的帮助。有效。但是如果我想通过一个方法在类 c1 中填充我的 ArrayList,那么当我在另一个类中使用 ArrayList 时,如何确保出现相同的更改?
  • @VijendraSinghAswal 您也可以在static 方法中执行此操作,并且您必须确保在使用list 之前应调用此static 方法。
  • 您能否举一个在静态方法中调用它的示例。我试过了,但只有在我放入静态块时才有效。
  • @sathishvisa 我不明白你的要求,你有什么问题?
  • @sathishvisa 如果您将List&lt;Whatever&gt; 声明为static,那么您应该在静态块中对其进行初始化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-22
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2013-02-01
相关资源
最近更新 更多