To read an ArrayList
returned from a method in another class in Java, you can use the method just like any other method. You can call the method, pass any necessary arguments, and store the returned ArrayList
in a variable for further processing.
Here is an example of how you can read an ArrayList
returned from a method in another class in Java:
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> list = DataProvider.getData(); for (String item : list) { System.out.println(item); } } } class DataProvider { public static ArrayList<String> getData() { ArrayList<String> list = new ArrayList<>(); list.add("Item 1"); list.add("Item 2"); list.add("Item 3"); return list; } }
In this example, the Main
class has a main
method that calls the getData
method of the DataProvider
class and stores the returned ArrayList
in a variable named list
.
The main
method then iterates over the ArrayList
using a for-each loop and prints each item to the console using the System.out.println
method.
This code will call the getData
method of the DataProvider
class, read the returned ArrayList
, and print its contents to the console. You can modify the code to perform other operations with the ArrayList
, such as sorting it or searching for specific items.
Keep in mind that this is just one way to read an ArrayList
returned from a method in another class in Java. You can use different techniques and libraries to achieve the same result, such as using the List
interface or the Collections
class. You may also need to handle exceptions and other error conditions.