Как заполнить arraylist java при создании
Перейти к содержимому

Как заполнить arraylist java при создании

  • автор:

How to Initialize an ArrayList

In this tutorial, you will learn multiple ways to initialize an ArrayList.

1. ArrayList Initialization using Arrays.asList() method

The asList() method of Arrays class converts an array to ArrayList. This is a perfect way to initialize an ArrayList because you can specify all the elements inside asList() method.


Here, we have initialized an ArrayList of string type using Arrays.asList() method. We have specified three string elements inside asList() , these elements are added as arraylist elements. As you can see, when we print the arraylist elements, it prints the three strings that we passed inside asList() .

Another example: Using Arrays.asList() to initialize an ArrayList of integer type.


2. Anonymous inner class method to initialize an ArrayList

Here, we initialize an ArrayList using anonymous inner class. Note the double curly braces. The elements are specified using add().



3. Normal way of ArrayList initialization

This is the most common and frequently used method of initializing an array. Here we are using add() method of ArrayList class to add elements to an ArrayList.


In the following example, we have created an ArrayList with the name books . We can add as many elements as we want by calling add() method. Please keep in mind the type of the ArrayList. In this example, we have created an arraylist of string type so we are specifying strings in add() method. If the arraylist is of integer type, you need to specify the numbers in add() method else the program will throw compilation error.

4. Initializing an ArrayList with multiple same elements using Collections.ncopies()

Collections.ncopies() method is used, when we need to initialize the ArrayList with multiple same elements. For example, if you want an ArrayList with 50 elements and all elements as 10 then you can call the method like this: = new ArrayList<Integer>(Collections.nCopies(50, 10))


count is number of elements and element is the item value

In the following example, we have initialized an array with 10 elements and all the elements are 5.

Recommended articles:

Top Related Articles:

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.


Hi i used the anonymous inner class way to initialize an arrayList but i get the error below:

The type java.util.function.Consumer cannot be resolved. It is indirectly referenced from required .class files

Can you hint me as to what i have missed ?

may be u are missing import statement

public class Initialization2 <

public static void main(String args[]) <
final ArrayList cities = new ArrayList() <

In this code I have declared the ArrayList as “final” so it should not allow any modifications, like any integer variable marked as final cannot be changed once it is assigned.
But it allows the modification as I have added one more object “Goa” to cities ArrayList.

Please explain.

@Shivam in the above example…u r making reference variable as final so,if u want to again assign reference variable cities= new ArrayList();// you will get warning

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


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-64c7e8568c09e576774177/] Output [crayon-64c7e8568c0a2384555463/] 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?

Shashanth's user avatar

Macarse's user avatar

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:

Tom's user avatar

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:

List.of(. ) will give you an immutable List , so it cannot be changed.
Which is what you want in most cases where you’re prepopulating it.

This does not allow null elements.

Java 8 or earlier:

Arrays.asList(. ) 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.

This does allow null elements.

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

Christoffer Hammarström's user avatar

If you need a simple list of size 1:

If you need a list of several objects:

Peter Mortensen's user avatar

With Guava you can write:

In Guava there are also other useful static constructors. You can read about them here.

Paweł Adamski's user avatar

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 —


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 :

Mark's user avatar

You could create a factory method:

But it’s not much better than your first refactoring.

For greater flexibility, it can be generic:

Peter Mortensen's user avatar

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:

Peter Mortensen's user avatar

Mohit Tyagi's user avatar

Simply use below code as follows.

KeLiuyue's user avatar

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.

Donald Raab's user avatar

(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, especially if you need an unbounded list or need to use inheritance.

Dmitriy Popov's user avatar

You can use the below statements:

Code Snippet:

Java 9 has the following method to create an immutable list:

which is easily adapted to create a mutable list, if required:

Similar methods are available for Set and Map .

But since you complained of wanting an ArrayList, you should first know that ArrayList is a subclass of List and you could simply add this line:

Although, that might make you complain about ‘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 the time of initialization). And if that’s an option for you:

In case you don’t care about the minor performance differences then you can also copy an array to an ArrayList very simply:

Okay, but in the future, you need a bit more than just the place name, you need a country code too. Assuming this is still a predefined list that 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.

☕ Учебник по Java: списочный массив ArrayList

☕ Учебник по Java: списочный массив ArrayList

ArrayList – это реализация динамического использования массива в Java. При использовании массива часто приходится задумываться о требуемом размере, а ArrayList является списком, который увеличивается и уменьшается при необходимости. Этот класс является имплементацией интерфейса (interface) List из Collection Framework, который расположен в пакете java.utils . В самом классе есть базовые методы добавления и удаления, а также методы, которые возвращают размер списка; очистка по индексу или же по значению и т. д.

говоря, ArrayList является динамическим массивом, который сам определяет размер. При этом нет необходимости задавать какие-то конфигурации.

Создание объекта

Существуют несколько конструкторов у ArrayList для создания объекта. Каждый из этих видов имеет свои использования и преимущества. Давайте пройдемся по каждому и рассмотрим, где и как используется каждый из данных видов:

1. ArrayList() – простое объявление списка и наиболее часто используемое. Объявляется данный список обычно в конструкторе, который будет использоваться внутри объекта, например, имплементация кэширования и временного хранения в памяти. Является самым простым и удобным объявлением списочного массива в Java.

2. ArrayList(int initialCapacity) – объявление списка с указанием размера преимущественно для случаев, когда будет использоваться большое количество данных и в целях оптимизации следует задавать уже большой размер. Например, используется в случаях, когда список увеличивается с каждым вызовом метода в классе. Размер списка растет с нелинейной скоростью и, если заранее известно, что список будет увеличиваться и будет достигать больших размеров (больше 1e3 элементов), оптимально будет задать изначальный размер и резервировать количество мест заранее.

3. ArrayList(Collection c) – объявления списка с уже имеющимся списком, элементы которого были переданы конструктору.

Добавление элементов

Для того чтобы добавить элемент в список, используется простая функция add . Для этого метода есть разновидности:

1. add(E e) – добавление элемента в конец списка. Это функция является возвращаемой. Если элемент был добавлен в список, то ответ – true , иначе – false .

2. add(int index, E element) – в данном методе добавление элемента происходит в определенную позицию (index), а все последующие элементы двигаются слева направо. Метод эффективен для небольших размеров списка (когда размер списка не более

100 элементов). В ином случае – если в программе происходит много сдвигов, то лучше использовать LinkedList.

3. addAll(Collection ) – добавление списка элементов в конец добавляемого списка. То есть, при вызове данного метода в конец списка добавляются все элементы в таком же порядке.

4. addAll(int index, Collection ) – это смесь добавления списка и также добавления элемента в определенную позицию. В этом методе в позицию index производится добавление всех элементов из списка, а все последующие элементы смещаются направо.

Удаление элементов

В ArrayList, существуют методы для удаления элементов. Всего существуют 3 метода для удаления элемента:

1. remove(int index) – удаление осуществляется, используя индекс определенного элемента. То есть, передается порядковый номер элемента и этот элемента удаляется из списка. Не забываем, что индекс начинается с 0.

2. remove(object o) – метод удаляет первый встретившийся элемент, который равняется переданному объекту в параметрах. Если проще, то метод проходится по всему списку и ищет элемент, который равняется удаляемому объекту и при нахождении удаляет только первый встретившийся.

3. removaAll(Collection c) – данный метод удаляет все элементы, находящиеся в передаваемом списке.

Вспомогательные методы

В Arraylist встречаются различные методы, которые являются вспомогательными при различных условиях:

1. size() – возвращает размер списка.

2. sort(Comparator c) – происходит сортировка элементов по заданным параметрам Comparator . Есть уже значения по умолчанию у Comparator , которыми можно пользоваться, Comparator.naturalOrder() , а также Comparator.reverseOrder() .

3. toArray() – данный метод превращает список в массив. Он возвращает массив объектов ( Object[] ), но можно вернуть желаемый тип данных и для этого потребуется в метод toArray(Array a) передать уже созданный массив.

4. isEmpty() – проверка списка на наличие элементов. Если список пустой, то возвращает true , в противном случае – false .

5. indexOf(Object o) – метод возвращает позицию передаваемого элемента, и, если элемент не был найден, возвращает -1.

6. clear() – удаляет все элементы из списка.

7. clone() – метод копирует список. После копирования нужно привести к необходимому классу, то есть type casting . Когда список клонируется, создается отдельный независимый объект и удаление родительского списка не влияет на элементы нового списка.

Также можно прочитать более подробно про все существующие методы ArrayList в документации Oracle по ссылке.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *