Return an ArrayList in Java

Mohd Ebad Naqvi Dec 21, 2022 Jun 13, 2021 Java Java ArrayList
  1. Return an ArrayList From a Non-Static Function in Java
  2. Return an ArrayList From a Static Function in Java
Return an ArrayList in Java

An ArrayList is a resizable class of java.util package. It is a scalable array, which means that the size of an array can be modified whenever you want. However, it can be a little slow to use at times.

In this tutorial, we will return an ArrayList from a function inside a class in Java.

Return an ArrayList From a Non-Static Function in Java

We will work with a function that creates and returns an ArrayList of some size. We will try to invoke this function in another class. This function is non-static, so an object of the class will be needed to invoke it.

In the following code, we create such a function.

import java.util.ArrayList;
public class ClassA {
    public static void main(String args[])
    {
        ClassB m1 = new ClassB();
        List listInClassA = m1.myNumbers();
        System.out.println("The List is "+listInClassA);
    }
}
public class ClassB {
        public ArrayList<Integer> myNumbers()    {
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        numbers.add(10);
        numbers.add(15);
        numbers.add(30);
        return(numbers);
    }
}

Output:

The List is [10, 15, 30]

The function myNumbers() is not static. So, we need to create an instance of ClassB in ClassA. Now we will have access to the ArrayList method myNumbers() of ClassB.

Return an ArrayList From a Static Function in Java

A static function can be accessed or invoked without creating an object of the class to which it belongs.

If the static method is to be called from outside its parent class, we have to specify the class where that static function was defined.

We can modify our code slightly while working with a static function.

import java.util.ArrayList;
public class ClassA {
    public static void main(String args[])
    {
        List listInClassA = classB.myNumbers();
        System.out.println("The List is "+listInClassA);
    }
}
public class ClassB {
        public static ArrayList<Integer> myNumbers()    {
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        numbers.add(10);
        numbers.add(15);
        numbers.add(30);
        return(numbers);
    }
}

Output:

The List is [10, 15, 30]

In the above example, we referred to the function from classB in classA without creating an object of classB.

Related Article - Java ArrayList

  • Sort Objects in ArrayList by Date in Java
  • Find Unique Values in Java ArrayList
  • Vector and ArrayList in Java
  • Differences Between List and Arraylist in Java
  • Compare ArrayLists in Java
  • Merge Sort Using ArrayList in Java