Return an ArrayList in Java [2 ways]

In this post, we will learn how to return an ArrayList in Java. There are two kinds of methods in Java

1. static method

2. non-static method

Read Also: Create ArrayList with values in Java

We will look into both of them for returning ArrayList. Let's dive deep into the topic:

Return ArrayList in Java

1. Returning ArrayList for static method


You might already know that static methods can be called with the help of the class name. Below are the steps to perform for returning an ArrayList from a static method:

1. Create a method that has ArrayList as the return type.

2. Create an ArrayList object

3. Add the data to the ArrayList

4. Last step is to return the ArrayList

import java.util.ArrayList;
public class ReturnArrayList {
    public static ArrayList<String> sampleMethod()
    {
        ArrayList<String> arrlist = new ArrayList<String>();
        arrlist.add("First");
        arrlist.add("Second");
        arrlist.add("Third");
        return arrlist;
    }
    public static void main(String args[]) 
    {
        ArrayList<String> list = ReturnArrayList.sampleMethod();
        System.out.println(list);
    }
}


Output:
[First, Second, Third]


2. Returning ArrayList for non-static method


The methods that do not have the static keyword in the method signature are called non-static methods. They are usually defined under a normal class name.

You can not call non-static methods with the help of a class name. You need to create the object of the class and then call the non-static method using that object.

The method of returning ArrayList for non-static methods is similar to returning ArrayList for static methods with just one caveat as shown below in the example:

import java.util.ArrayList;
public class ReturnArrayList2 {
    public static ArrayList<String> sampleMethod()
    {
        ArrayList<String> arrlist = new ArrayList<String>();
        arrlist.add("First");
        arrlist.add("Second");
        arrlist.add("Third");
        return arrlist;
    }
    public static void main(String args[]) 
    {
        ReturnArrayList2 obj = new ReturnArrayList2();
        ArrayList<String> list = obj.sampleMethod();
        System.out.println(list);
    }
}


Output:
[First, Second, Third]


That's all for today. Please mention in the comments if you have any questions related to returning ArrayList in Java with examples.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry