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);
}
}
}
Asked
Active
Viewed 388 times
0

FiReTiTi
- 5,597
- 12
- 30
- 58

Sandeep Raj Urs
- 53
- 10
-
`for(int i=0;i<=t.list.size();i++){` You're going past the the end of the array by one. – 001 Nov 28 '16 at 18:34
-
Anonymous suggestion. Use getter and setters for fields in class. – Naman Nov 28 '16 at 18:36
-
`Test3.test()` calls `Testing.testmtd()`. That function creates a new `Test3`, and that object has a null `list`. – 001 Nov 28 '16 at 18:40
-
@JohnnyMopp can you please help me over that where to modify my code.But my intension is to get the Array list data in Testing class. – Sandeep Raj Urs Nov 28 '16 at 18:47
-
Posted an answer for you. – 001 Nov 28 '16 at 18:52
1 Answers
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