MD TALIB ALAM MD TALIB ALAM - 3 months ago 21
Java Question

ArrayList content not showing while accessing from another class

I have defined ArrayList and added few data into it by one class

Class containing ArrayList defination

package practice;
import java.util.ArrayList;
class Prac {
static ArrayList<Integer> ar1=new ArrayList<Integer>();
public static void it(){
ar1.add(1);
ar1.add(2);
ar1.add(2);
ar1.add(2);
ar1.add(2);
ar1.add(2);
ar1.add(2);
ar1.add(2);
}
}
public class Exet{
public static void main(String args[]){
Prac.it();
}
}


Then i want to see the data stored into the ArrayList by another class by Iterating it my second class is as follows

second class

package practice;
import practice.Prac;
import java.util.*;
public class StackOver {
public static void main(String args[]){
System.out.println(Prac.ar1.isEmpty());
Iterator<Integer> it=Prac.ar1.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}


but when i am executing second class it is not showing anything so my question is, am i doing something unprincipled (then what is the reason) or is there any way out, a detailed explanation will help me understand it thanks in advance

Answer

Declaring a method static does not mean it will be run when your class is loaded.

in your first program you called the method which populates the arraylist. in the second program you never called it.

add a static block to your first program and populate your arraylist in this static block if you want it to be available to your other class or you can make a call to "it()" method from the static block of the first program.

when your first class is loaded your static block will be run and your arraylist would be initialized.

change your first program to the below:

public static ArrayList<Integer> ar1=new ArrayList<Integer>();
static {
        ar1.add(1);
        ar1.add(2);
        ar1.add(2);
        ar1.add(2);
        ar1.add(2);
        ar1.add(2);
        ar1.add(2);
        ar1.add(2); 
}

change the scope of your arraylist so that it is available to your other class and initialize your arraylist in the static block as shown.

a simpler solution would be to call the method which initializes the arraylist in a static block of your first program as shown below:

public static ArrayList<Integer> ar1 = new ArrayList<Integer>();
static {
        it();           
}

you can access your arraylist as follows in your other class:

Prac.ar1