假设我有一个班级
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时,如何确保出现相同的更改?
答案 0 :(得分:7)
在您的代码中,您应该调用c1
构造函数以填充ArrayList
。所以你需要:
public c2() {
new c1();
System.out.println("c1.list.size() = " + c1.list.size()); //Prints 0
}
但这并不好。最好的方法是使用static
类中的c1
块代码进行静态初始化:
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<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;
}