Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a public static ArrayList from various classes?

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?

like image 952
Vini Avatar asked Feb 13 '26 00:02

Vini


1 Answers

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;
}
like image 67
Luiggi Mendoza Avatar answered Feb 15 '26 14:02

Luiggi Mendoza