Class ArrayList<E>
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:
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.
Java ArrayList Class
In this tutorial, we will learn about the ArrayList class in Java. We will learn about different operations and methods of the arraylist with the help of examples.
The ArrayList class of the Java collections framework provides the functionality of resizable-arrays.
It implements the List interface.
Java ArrayList Implementation
Java ArrayList Vs Array
In Java, we need to declare the size of an array before we can use it. Once the size of an array is declared, it’s hard to change it.
To handle this issue, we can use the ArrayList class. It allows us to create resizable arrays.
Unlike arrays, arraylists can automatically adjust its capacity when we add or remove elements from it. Hence, arraylists are also known as dynamic arrays.
Creating an ArrayList
Before using ArrayList , we need to import the java.util.ArrayList package first. Here is how we can create arraylists in Java:
Here, Type indicates the type of an arraylist. For example,
In the above program, we have used Integer not int. It is because we cannot use primitive types while creating an arraylist. Instead, we have to use the corresponding wrapper classes.
Here, Integer is the corresponding wrapper class of int . To learn more, visit the Java wrapper class.
Example: Create ArrayList in Java
Output
In the above example, we have created an ArrayList named languages .
Here, we have used the add() method to add elements to the arraylist. We will learn more about the add() method later in this tutorial.
Basic Operations on ArrayList
The ArrayList class provides various methods to perform different operations on arraylists. We will look at some commonly used arraylist operations in this tutorial:
- Add elements
- Access elements
- Change elements
- Remove elements
1. Add Elements to an ArrayList
To add a single element to the arraylist, we use the add() method of the ArrayList class. For example,
Output
In the above example, we have created an ArrayList named languages . Here, we have used the add() method to add elements to languages .
To learn more, visit the Java ArrayList add().
Other way to add elements to arraylist
We can also pass an index number as an additional parameter to the add() method to add an element at the specified position. For example,
We can also add all elements of a collection (set, map) to an arraylist using the addAll() method. For example,
2. Access ArrayList Elements
To access an element from the arraylist, we use the get() method of the ArrayList class. For example,
Output
In the above example, we have used the get() method with parameter 1 . Here, the method returns the element at index 1.
To learn more, visit the Java ArrayList get().
We can also access elements of the ArrayList using the iterator() method. To learn more, visit Java ArrayList iterator().
3. Change ArrayList Elements
To change elements of the arraylist, we use the set() method of the ArrayList class. For example,
Output
In the above example, we have created an ArrayList named languages . Notice the line,
Here, the set() method changes the element at index 2 to JavaScript .
To learn more, visit the Java ArrayList set().
4. Remove ArrayList Elements
To remove an element from the arraylist, we can use the remove() method of the ArrayList class. For example,
Output
Here, the remove() method takes the index number as the parameter. And, removes the element specified by the index number.
We can also remove all the elements from the arraylist at once. To learn more, visit
Methods of ArrayList Class
In the previous section, we have learned about the add() , get() , set() , and remove() method of the ArrayList class.
Besides those basic methods, here are some more ArrayList methods that are commonly used.
| Methods | Descriptions |
|---|---|
| size() | Returns the length of the arraylist. |
| sort() | Sort the arraylist elements. |
| clone() | Creates a new arraylist with the same element, size, and capacity. |
| contains() | Searches the arraylist for the specified element and returns a boolean result. |
| ensureCapacity() | Specifies the total element the arraylist can contain. |
| isEmpty() | Checks if the arraylist is empty. |
| indexOf() | Searches a specified element in an arraylist and returns the index of the element. |
If you want to learn about all the different methods of arraylist, visit Java ArrayList methods.
Iterate through an ArrayList
We can use the Java for-each loop to loop through each element of the arraylist. For example,
Output
Frequently Asked Questions
Some of the major differences between ArrayList and LinkedList in Java are:
| ArrayList | LinkedList |
| Implements List interface | Implements List , Queue , and Deque interfaces. |
| Stores a single value. | Stores 3 values: data, previous and next address |
| Provides the functionality of a resizable array. | Provides the functionality of doubly-linked list |
We can convert the ArrayList into an array using the toArray() method. For example,
Output
In the above example, the toArray() method converts the languages arraylist to an array and stores it in arr . To learn more, visit Java ArrayList toArray().
We use the asList() method of the Arrays class. To use asList() , we must import the java.util.Arrays package first. For example,
Output
In the above program, we first created an array arr of the String type. Notice the expression,
Here, the asList() method converts the array into an arraylist.
We use the Arrays.asList() method to create and initialize an arraylist in a single line. For example,
We use the toString() method of the ArrayList class to convert an arraylist into a string. For example,
Output
Here, the toString() method converts the whole arraylist into a single string. To learn more, visit Java ArrayList toString().
We can also create an arraylist using the List interface. It’s because the ArrayList class implements the List interface. Let’s see an example,
Initialize ArrayList with values in Java
In this article, we will learn to initialize ArrayList with values in Java.
ArrayList is an implementation class of List interface in Java. It is used to store elements. It is based on a dynamic array concept that grows accordingly.
We can Initialize ArrayList with values in several ways. Let’s see some of them with examples.
Table of Contents
Using Arrays.asList()
We can use Arrays.asList() method and pass it to ArrayList’s constructor to initialize ArrayList with values in java. This approach is useful when we already have data collection.
Initialize ArrayList with String values
When you pass Arrays.asList() to ArrayList constructor, you will get ArrayList object and you can modify the ArrayList the way you want.
💡 Did you know?
If you are using Array.asList() without ArrayList constructor to initialize list, then You can not structurally modify list after creating it.
Although you can use list.set() method to change elements.
As you can see, 2nd element of the list changed from Mango to Banana
intialize ArrayList with Integer values
intialize ArrayList with float values
Using Stream in Java 8
If you are working with Java 8 or higher version, then we can use of() method of Stream to initialize an ArrayList in Java. See the example below.
You can add or remove element from the list with this approach.
Using Factory Method in java 9
In Java 9, Java added some factory methods to List interface to create immutable list in Java. It can be used to initialize ArrayList with values in a single line statement.
💡 Did you know?
As the list is immutable, you can not add/remove new element and you can not use list'set() method to change elements.
Using double braces
Here is another approach to initialize ArrayList with values in Java, but it is not recommended because it creates an anonymous class internally that takes to verbose code and complexity.
That’s all about how to Initialize ArrayList with Values in Java.
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
PriorityQueue in Java 8
How to Deep Copy Arraylist in Java
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 […]

Return ArrayList in Java
Table of ContentsReturn ArrayList in Java From a Static MethodReturn ArrayList in Java From a Non-static MethodConclusion 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 […]

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-64838f6227624318541474/] Output [crayon-64838f622762a460682055/] 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 […]
Initialization of an ArrayList in one line
I wanted to create a list of options for testing purposes. At first, I did this:
Then, I refactored the code as follows:
Is there a better way to do this?
![]()
![]()
34 Answers 34
It would be simpler if you were to just declare it as a List — does it have to be an ArrayList?
Or if you have only one element:
This would mean that places is immutable (trying to change it will cause an UnsupportedOperationException exception to be thrown).
To make a mutable list that is a concrete ArrayList you can create an ArrayList from the immutable list:
And import the correct package:
![]()
Actually, probably the «best» way to initialize the ArrayList is the method you wrote, as it does not need to create a new List in any way:
The catch is that there is quite a bit of typing required to refer to that list instance.
There are alternatives, such as making an anonymous inner class with an instance initializer (also known as an «double brace initialization»):
However, I’m not too fond of that method because what you end up with is a subclass of ArrayList which has an instance initializer, and that class is created just to create one object — that just seems like a little bit overkill to me.
What would have been nice was if the Collection Literals proposal for Project Coin was accepted (it was slated to be introduced in Java 7, but it’s not likely to be part of Java 8 either.):
Unfortunately it won’t help you here, as it will initialize an immutable List rather than an ArrayList , and furthermore, it’s not available yet, if it ever will be.
The simple answer
Java 9 or later:
This will give you an immutable List , so it cannot be changed.
Which is what you want in most cases where you’re prepopulating it.
Java 8 or earlier:
This will give you a List * backed by an array, so it cannot change length.
But you can call List.set(. ) , so it’s still mutable.
* Implementation detail: It’s a private nested class inside java.util.Arrays , named ArrayList ,
which is a different class from java.util.ArrayList , even though their simple names are the same.
Static import
You can make Java 8 Arrays.asList even shorter with a static import:
Any modern IDE * will suggest and do this for you.
I don’t recommend statically importing the List.of method as just of , because it’s confusing.
* For example, in IntelliJ IDEA you press Alt+Enter and select Static import method.
Using Stream s
Why does it have to be a List ?
With Java 8 or later you can use a Stream which is more flexible:
You can concatenate Stream s:
Or you can go from a Stream to a List :
But preferably, just use the Stream without collecting it to a List .
If you specifically need a java.util.ArrayList *
If you want to both prepopulate an ArrayList and add to it afterwards, use
or in Java 8 or earlier:
or using Stream :
Then you can add to it after construction:
But again, it’s better to just use the Stream directly instead of collecting it to a List .
*You probably don’t need specifically an ArrayList . To quote JEP 269:
There is a small set of use cases for initializing a mutable collection instance with a predefined set of values. It’s usually preferable to have those predefined values be in an immutable collection, and then to initialize the mutable collection via a copy constructor.
Program to interfaces, not to implementations
You said you’ve declared the list as an ArrayList in your code, but you should only do that if you’re using some member of ArrayList that’s not in List .
Which you are most likely not doing.
Usually you should just declare variables by the most general interface that you are going to use (e.g. Iterable , Collection , or List ), and initialize them with the specific implementation (e.g. ArrayList , LinkedList or Arrays.asList() ).
Otherwise you’re limiting your code to that specific type, and it’ll be harder to change when you want to.
For example, if you’re passing an ArrayList to a void method(. ) :
Another example would be always declaring variable an InputStream even though it is usually a FileInputStream or a BufferedInputStream , because one day soon you or somebody else will want to use some other kind of InputStream .
![]()
If you need a simple list of size 1:
If you need a list of several objects:
![]()
With Guava you can write:
In Guava there are also other useful static constructors. You can read about them here.
![]()
With java-9 and above, as suggested in JEP 269: Convenience Factory Methods for Collections, this could be achieved using collection literals now with —
A similar approach would apply to Map as well —
which is similar to Collection Literals proposal as stated by @coobird. Further clarified in the JEP as well —
Alternatives
Language changes have been considered several times, and rejected:
Project Coin Proposal, 29 March 2009
Project Coin Proposal, 30 March 2009
JEP 186 discussion on lambda-dev, January-March 2014
The language proposals were set aside in preference to a library-based proposal as summarized in this message.
Collection literals didn’t make it into Java 8, but it is possible to use the Stream API to initialize a list in one rather long line:
If you need to ensure that your List is an ArrayList :
![]()
You could create a factory method:
But it’s not much better than your first refactoring.
For greater flexibility, it can be generic:
![]()
In Java 9 we can easily initialize an ArrayList in a single line:
This new approach of Java 9 has many advantages over the previous ones:
![]()
![]()
Simply use below code as follows.
![]()
About the most compact way to do this is:
Here is another way:
With Eclipse Collections you can write the following:
You can also be more specific about the types and whether they are Mutable or Immutable.
You can also do the same with Sets and Bags:
Note: I am a committer for Eclipse Collections.
![]()
(Should be a comment, but too long, so new reply). As others have mentioned, the Arrays.asList method is fixed size, but that’s not the only issue with it. It also doesn’t handle inheritance very well. For instance, suppose you have the following:
The above results in a compiler error, because List<B> (which is what is returned by Arrays.asList) is not a subclass of List<A> , even though you can add Objects of type B to a List<A> object. To get around this, you need to do something like:
This is probably the best way to go about doing this, esp. if you need an unbounded list or need to use inheritance.
![]()
You can use the below statements:
Code Snippet:
But since you complained of wanting an ArrayList, you should firstly know that ArrayList is a subclass of List and you could simply add this line:
Although, that might make you complain of ‘performance’.
In that case it doesn’t make sense to me, why, since your list is predefined it wasn’t defined as an array (since the size is known at time of initialisation). And if that’s an option for you:
In case you don’t care of the minor performance differences then you can also copy an array to an ArrayList very simply:
Okay, but in future you need a bit more than just the place name, you need a country code too. Assuming this is still a predefined list which will never change during run-time, then it’s fitting to use an enum set, which would require re-compilation if the list needed to be changed in the future.