Class ArrayList
Type Parameters: E — the type of elements in this list All Implemented Interfaces: Serializable , Cloneable , Iterable , Collection , List , RandomAccess Direct Known Subclasses: AttributeList , RoleList , RoleUnresolvedList
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null . In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector , except that it is unsynchronized.)
The size , isEmpty , get , set , iterator , and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be «wrapped» using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:
List list = Collections.synchronizedList(new ArrayList(. ));
The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
This class is a member of the Java Collections Framework.
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
How to use Objects and Lists in Java as Return Types instead of Tuples
Submitted by matt_eaton on Sun, 03/10/2019 — 02:31 PM
Tags
Java is a very concrete and powerful language. In the last 20 years Java has become a staple in enterprise, mobile, and server side computing. However, if you’re coming over to Java from languages like Swift, Python, or Haskell you might say be wondering about different functional aspects of Java. One question I had is, «How come Java does not support n-value heterogeneous return type tuples?» The answer is that Java’s methods are intended to have one return type per method call. If multiple return types are desired, then this would be a call break up these pieces of data into different methods calls or wrap these types in a custom object. Coming to Java from a more functional language can be a mind shift in this way, but in Java’s case it’s a shift that makes sense when thinking about how the language works. So in this tutorial I wanted to provide two examples of returning custom objects and lists from a method call, instead of a tuple. Let’s jump in!
Returning Custom Objects 🚀
First let’s look at a technique to return heterogeneous types and that is of course wrapped in an object. Returning a custom Java object from a method is a staple of Java programming and can be used to return multiple types or the same set of types. One thing to note is that these types in Java all conform to the same context. Let’s take a look at for example the ErrorWrapper custom class below. This class takes in a custom message and error code. Two different types, but all from the same context. This allows the custom object to be created and returned from a method call to be used throughout your program. Here is an example below:
public class ErrorWrapper { private String message = ""; private Integer errorCode = 0; public ErrorWrapper(String m, Integer c) { message = m; errorCode = c; } public String getMessage() { // Do some logic here based upon error code and message return message; } public Integer getErrorCode() { return errorCode; } } public ErrorWrapper reasonAboutErrorException(Exception e) { ErrorWrapper errorWrapper = new ErrorWrapper(e.getMessage(), 100); // Perform some logic on errorWrapper return errorWrapper; }
Returning List Types 📝
The heterogeneous object is probably a bit more work, but returning a set of homogeneous types can be a lot more straight forward. In a case where multiple strings or integers are needed, a simple Java list is all that is needed to be assembled. A Java List is nothing more than a collection or an array of same types assembled in a method call and returned accordingly. For example see the following code below:
public List String> reasonAboutException(Exception e) { List String> returnStrings = new ArrayList String>(); returnStrings.add(e.getMessage()); returnStrings.add(e.getCause().toString()); return returnStrings; } List String> inferredExceptionList = reasonAboutException(e); String string1 = inferredExceptionList.get(0); String string2 = inferredExceptionList.get(1);
In Summary ⌛️
I hope this short tutorial was helpful in learning more about returning objects and lists in Java instead of tuples. Java is a great language and is a cornerstone of object orientated programming. One might argue that there is no need for using tuples in Java, and I would to agree. Only time will tell if these more functional aspects are integrated into the language at over time. I hope you enjoyed this and if you have any questions, comments, or concerns, please leave a comment below and I will try to respond as soon as possible. Thank you!
Member for
Long time mobile team lead with a love for network engineering, security, IoT, oss, writing, wireless, and mobile. Avid runner and determined health nut living in the greater Chicagoland area.