- Returning Collections From Methods in Java
- Optional Lessons
- Return an ArrayList in Java
- Return an ArrayList From a Non-Static Function in Java
- Return an ArrayList From a Static Function in Java
- Related Article — Java ArrayList
- Return ArrayList in Java
- Return ArrayList in Java From a Static Method
- Return ArrayList in Java From a Non-static Method
- Further reading:
- Conclusion
- Was this post helpful?
- You may also like:
- Update Value of Key in HashMap in Java
- Create Array of Linked Lists in Java
- Return ArrayList in Java
- Create List with One Element in Java
- How to Add Multiple Values for Single Key In HashMap in Java
- [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
- Create ArrayList of Objects in Java
- How to remove element from Arraylist in java while iterating
- Print HashMap in Java
- Print LinkedList in java
- Share this
- Related Posts
- Author
- Related Posts
- Update Value of Key in HashMap in Java
- Create Array of Linked Lists in Java
- Create List with One Element in Java
- How to Add Multiple Values for Single Key In HashMap in Java
- [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
- Create ArrayList of Objects in Java
Returning Collections From Methods in Java
Writing software often means fetching and returning data. In an object-oriented language like Java, we generally express data in terms of properties of a class. Unlike many newer OO languages, Java doesn’t offer properties as a first-class construct, so we instead use JavaBean getters and setters, in order to maintain encapsulation. As a result, most of us have grown accustomed to writing code like the following:
public class MyClass private String data;
public String getData() < return this.data; >
public void setData(String data) < this.data = data; >
>
In the example above, we see a simple class with a simple property: a String called data. Of course, data can either contain a value, or it can be null.
How do we deal with Collection -type properties? Let’s fabricate a simple class that encapsulates a List :
public class MyClass private List myStrings;>
We have a field — a List of String s — called myStrings , which is encapsulated in MyClass . Now, we need to provide accessor methods:
public class MyClass private List myStrings; public void setMyStrings(List s) this.myStrings = s;
> public List getMyStrings() return this.myStrings;
>>
Here we have a properly-encapsulated — if verbose — class. So we’ve done good, right? Hold that thought.
Optional Lessons
Consider the Optional class, introduced in Java 8. By now, you’ve probably heard the mantra that you should never return null from a method that returns an Optional . Why? Consider the following contrived example:
public class Foo private String bar; public Optional getBar() // don't actually ever do this
return (bar == null) ? null : Optional.of(bar);
>>
Return an ArrayList in Java
- Return an ArrayList From a Non-Static Function in Java
- Return an ArrayList From a Static Function 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 ArrayListInteger> myNumbers() ArrayListInteger> numbers = new ArrayListInteger>(); numbers.add(10); numbers.add(15); numbers.add(30); return(numbers); > >
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 ArrayListInteger> myNumbers() ArrayListInteger> numbers = new ArrayListInteger>(); numbers.add(10); numbers.add(15); numbers.add(30); return(numbers); > >
In the above example, we referred to the function from classB in classA without creating an object of classB .
Related Article — Java ArrayList
Copyright © 2023. All right reserved
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.
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.
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.
Further reading:
Print ArrayList in Java
Initialize ArrayList with values in Java
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?
You may also like:
Update Value of Key in HashMap in Java
Create Array of Linked Lists in Java
Return ArrayList in Java
Create List with One Element in Java
How to Add Multiple Values for Single Key In HashMap in Java
[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
Create ArrayList of Objects in Java
How to remove element from Arraylist in java while iterating
Print HashMap in Java
Print LinkedList in java
Share this
Related Posts
Author
Related Posts
Update Value of Key in HashMap in Java
Table of ContentsUsing the put() Method of HashMap Collection in JavaUsing the compute() Method of HashMap Collection in JavaUsing the merge() Method of the HashMap Collection in JavaUsing the computeIfPresent() Method of The HashMap Collection in JavaUsing the replace() Method of The HashMap Collection in JavaUsing the TObjectIntHashMap Class of Gnu.Trove Package in JavaUsing the […]
Create Array of Linked Lists in Java
Table of ContentsIntroductionLinked List in JavaApplication of Array of Linked ListsCreate Array of Linked Lists in JavaUsing Object[] array of Linked Lists in JavaUsing the Linked List array in JavaUsing the ArrayList of Linked Lists in JavaUsing the Apache Commons Collections Package Introduction In this article, we will look at how to Create an Array […]
Create List with One Element in Java
Table of ContentsUsing Collections.singletonList()Using Array.asList() method [ Immuatable list]Using new ArrayList with Array.asList() method [ Mutable list] In this post, we will see how to create List with One Element in java.. Using Collections.singletonList() This is best way to create List with single element if you need an immutable List. [crayon-64b808eb862d9878965735/] Output [crayon-64b808eb862df358993108/] If you […]
How to Add Multiple Values for Single Key In HashMap in Java
Table of ContentsHashMapCan HashMap Store Multiple Values AutomaticallyWays to Add Multiple Values for Single Key In HashMap in JavaUsing the Standard LibraryUsing Apache Commons LibraryUsing Google Guava LibraryUsing TreeSet as ValuesUsing a Wrapper ClassUsing Java TuplesUsing compute() Function in JDK 8Conclusion This article discusses the HashMap in Java and how to add multiple values for […]
[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]
Create ArrayList of Objects in Java
Table of ContentsUsing the add() method to create ArrayList of objects in javaUsing parameterized constructor to create ArrayList of objects in javaUsing addAll() method to create ArrayList of objects in javaConclusion In this tutorial, we will learn how to create ArrayList of objects in Java. We will create a Book class with different properties and […]