Suppose I have a class
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");
}
}
}
But if I access the same ArrayList in another class, I will get a list with SIZE = 0.
public class c2 {
public c2() {
System.out.println("c1.list.size() = " + c1.list.size()); //Prints 0
}
}
Why is this happening. If the variable is static, then why is a new list being generated for class c2? How can I make sure that I get the same ArrayList if I access it in a different class?
/****Revised code********/
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);
}
}
But if I access the same ArrayList in another class, I will get a list with SIZE = 0, irrespective of how many times I called AddToList method.
public class c2 {
public c2() {
System.out.println("c1.list.size() = " + c1.list.size()); //Prints 0
}
}
How can I make sure that same changes appear when I use the ArrayList in another class?
In your code as is, you should call the c1 constructor in order to fill the ArrayList. So you would need:
public c2() {
new c1();
System.out.println("c1.list.size() = " + c1.list.size()); //Prints 0
}
But this is not good. The best approach would be static initialization by using a static block code in c1 class:
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() {
}
}
As a recommendation from What does it mean to "program to an interface"?, it would be better to declare the variable as List<String> and create the instance as ArrayList:
public static List<String> list = new ArrayList<String>();
Another recommendation, use a static method to access to this variable instead of making it public:
private static List<String> list = new ArrayList<String>();
public static List<String> getList() {
return list;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With