Question: Using Java Hello, I am trying to pass an arraylist between two methods in different classes but I am getting null. When I call l

Using Java

Hello, I am trying to pass an arraylist between two methods in different classes but I am getting null. When I call "l = o.getList(l);" in the passObj2 methods in main l becomes null instead of the array. I would like "l" to have the array of "list" then pass l into "o.setObjb()" . I am trying to pass an Arraylist (list), in a class (ObjA), into another class (main). Once the Arraylist is passed into main, I would like to pass it back to the (ObjA) class in a different method (setObjB).

1. So first create an ArrayList in a class(ObjA)

2. Then call that ArrayList in another class(Main).

3. Then pass the data in the ArrayList into a different method in that class.(passObj2 in Main)

4. Finally pass the ArrayList back into the original class(ObjA) under a different method.(setObjB) Below is the code.

Below is the code.

public class ObjA {

ArrayList list = new ArrayList<>();

public void setObjA(ArrayList list) throws IOException{

//create an arraylist

ArrayList arr = new ArrayList<>();

arr.add("This is an ");

arr.add("array");

//Pass the arrays into list

list = arr;

return;

}

//getter to get the arraylist stored

public ArrayList getList(ArrayList list) {

return list;

}

//2nd method that the arraylist will be past to

public void setObjB(ArrayList list) throws IOException{

list = getList(list) ;

System.out.println("z " +list);

}

}

- -- - - - -

import java.io.IOException;

import java.util.ArrayList;

public class Main {

public static void main(String[] args) throws IOException {

// TODO Auto-generated method stub

ObjA obj = new ObjA();

ArrayList list = null;

passResult(obj, list);

passObj2(obj, list );

}

private static ObjA passResult(ObjA o, ArrayList l) throws IOException {

// TODO Auto-generated method stub

ObjA obj1 = new ObjA();

obj1=o;

obj1.setObjA(l);

System.out.println(obj1);

return o;

}

private static void passObj2(ObjA o, ArrayList l) throws IOException {

// This is the issue. l is not the array "list" in the other class, it is displaying as null. I am trying to make a call to get the arraylist in the other class.

l = o.getList(l);

System.out.print(l);

// l would like to pass the arraylist into the other method in the other class.

o.setObjB(l);

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!