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?