Table of Contents
This article discusses cases of returning an ArrayList in Java from a method.
An ArrayList in Java is a collection of elements of the same data type under a single variable name. In different cases, you can return an ArrayList from a method in Java. These cases are as given below.
- Returning ArrayList from a static method.
- Returning ArrayList from a non-static method.
Return ArrayList in Java From a Static Method
As you might know, static methods in Java do not need any class instance to call them. You can call a static method using the class name.
Returning an ArrayList from a static method is simple.
- Create a static method with the return type as
ArrayList
. - Create an ArrayList and instantiate it.
- Input the data into the list.
- Return the ArrayList.
Let us see an example code for the same.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package java2blog; import java.util.ArrayList; class retClass{ public static ArrayList<Integer> myFun() { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); return list; } } public class GetClass { public static void main(String [] args) { ArrayList<Integer> list = retClass.myFun(); for(int i=0;i<list.size();i++) { System.out.print(list.get(i)+" "); } System.out.println(); } } |
Output:
Return ArrayList in Java From a Non-static Method
The methods that you normally define under a normal class name are the non-static methods.
You can not directly call the non-static methods using the class name. For calling a non-static method, you would need to create an instance of the class and then call the method using that instance.
This method of returning the ArrayList is similar except that the receiving method must use the class instance to call the returning method.
Let us see the example code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package java2blog; import java.util.ArrayList; class retClass{ public ArrayList<Integer> myFun() { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); return list; } } public class GetClass { public static void main(String [] args) { retClass obj = new retClass(); ArrayList<Integer> list = obj.myFun(); for(int i=0;i<list.size();i++) { System.out.print(list.get(i)+" "); } System.out.println(); } } |
Output:
Further reading:
Conclusion
This is all about returning the ArrayList from a method in Java.
Hope you enjoyed reading the article. Stay tuned for more such articles. Happy Learning!