0
public class Test3 {

public ArrayList<String> list; 

//storing all data in this lsit

//test() is main test method where program gets triggered

@Test
public void test(){
    list=new ArrayList<String>(); 
    list.add("1");
    list.add("2");
    list.add("3");
    Testing t=new Testing(); 
    //creating object to call testmtd
    t.testmtd();
    System.out.println(list);
    }
}

public class Testing {
public void testmtd()  
{   
    Test3 t=new Test3();  
    //created object to access list of Test3 class

    System.out.println("run1");
    for(int i=0;i<=t.list.size();i++)
        {
        String data=t.list.get(i);  
        //here i am not able to access the data present in the list of Test3 class
        System.out.println(data);
        }
    }
}
FiReTiTi
  • 5,597
  • 12
  • 30
  • 58

1 Answers1

0

Test3.test() calls Testing.testmtd(). That function creates a new Test3, and that object has a null list.

You could modify the testmtd function to accept a Test3 parameter:

public void testmtd(Test3 t)  
{   
    System.out.println("run1");
    for(int i = 0; i < t.list.size(); i++) {  // Fixed the out of bounds issue
        String data=t.list.get(i);  
        System.out.println(data);
    }
}

Then, modify the way it's called:

public void test() {
    list=new ArrayList<String>(); 
    list.add("1");
    list.add("2");
    list.add("3");
    Testing t=new Testing(); 
    t.testmtd(this);     // Pass this object
    System.out.println(list);
}
001
  • 13,291
  • 5
  • 35
  • 66