Return ArrayList in Java

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 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.

Output:

India
China
Japan

Here we wrote simple utility method to take string as input and return ArrayList as output. This programs splits String by comma and return ArrayList.

You can also create new ArrayList and add elements one by one.

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.

Output:

1 2 3

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!

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *