The Wayback Machine - https://web.archive.org/web/20241114204737/https://www.geeksforgeeks.org/initialize-an-arraylist-in-java/
Open In App

Initialize an ArrayList in Java

Last Updated : 04 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.

  • ArrayList inherits AbstractList class and implements List interface.
  • ArrayList is initialized by a size, however the size can increase if collection grows or shrink if objects are removed from the collection.
  • Java ArrayList allows us to randomly access the list.
  • ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases (see this for details).
  • ArrayList in Java can be seen as similar to vector in C++.

java-arraylist

ArrayLists are dynamic, and knowing how to initialize them correctly can save you time and memory. If you want to explore different initialization techniques and best practices, the Java Programming Course provides hands-on examples and practical exercises.

Below are the various methods to initialize an ArrayList in Java:

Initialization with add()

  1. Syntax:
ArrayList<Type> str = new ArrayList<Type>();
str.add("Geeks");
str.add("for");
str.add("Geeks");
  1. Examples: 
Java
// Java code to illustrate initialization
// of ArrayList using add() method

import java.util.*;

public class GFG {
    public static void main(String args[])
    {

        // create a ArrayList String type
        ArrayList<String> gfg = new ArrayList<String>();

        // Initialize an ArrayList with add()
        gfg.add("Geeks");
        gfg.add("for");
        gfg.add("Geeks");

        // print ArrayList
        System.out.println("ArrayList : " + gfg);
    }
}

Output
ArrayList : [Geeks, for, Geeks]
  1. Examples: Using shorthand version of this method 
Java
// Java code to illustrate initialization
// of ArrayList using add() method

import java.util.*;

public class GFG {
    public static void main(String args[])
    {

        // create a ArrayList String type
        // and Initialize an ArrayList with add()
        ArrayList<String> gfg = new ArrayList<String>() {
            {
                add("Geeks");
                add("for");
                add("Geeks");
            }
        };

        // print ArrayList
        System.out.println("ArrayList : " + gfg);
    }
}

Output
ArrayList : [Geeks, for, Geeks]

Initialization using asList()

  1. Syntax:
ArrayList<Type> obj = new ArrayList<Type>(
Arrays.asList(Obj A, Obj B, Obj C, ....so on));
  1. Examples: 
Java
// Java code to illustrate initialization
// of ArrayList using asList method

import java.util.*;

public class GFG {
    public static void main(String args[])
    {

        // create a ArrayList String type
        // and Initialize an ArrayList with asList()
        ArrayList<String> gfg = new ArrayList<String>(
            Arrays.asList("Geeks",
                          "for",
                          "Geeks"));

        // print ArrayList
        System.out.println("ArrayList : " + gfg);
    }
}

Output
ArrayList : [Geeks, for, Geeks]

Initialization using List.of() method

  1. Syntax:
List<Type> obj = new ArrayList<>(
List.of(Obj A, Obj B, Obj C, ....so on));
  1. Examples: 
Java
// Java code to illustrate initialization
// of ArrayList using List.of() method

import java.util.*;

public class GFG {
    public static void main(String args[])
    {

        // create a ArrayList String type
        // and Initialize an ArrayList with List.of()
        List<String> gfg = new ArrayList<>(
            List.of("Geeks",
                    "for",
                    "Geeks"));

        // print ArrayList
        System.out.println("ArrayList : " + gfg);
    }
}

Output
ArrayList : [Geeks, for, Geeks]

Initialization using another Collection

  1. Syntax:
List gfg = new ArrayList(collection);
  1. Examples: 
Java
// Java code to illustrate initialization
// of ArrayList using another collection

import java.util.*;

public class GFG {
    public static void main(String args[])
    {

        // create another collection
        List<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
        arr.add(5);

        // create a ArrayList Integer type
        // and Initialize an ArrayList with arr
        List<Integer> gfg = new ArrayList<Integer>(arr);

        // print ArrayList
        System.out.println("ArrayList : " + gfg);
    }
}

Output
ArrayList : [1, 2, 3, 4, 5]

Initialization using  stream() and collect() methods

       1. Syntax:

ArrayList<Type> listName = Stream.of(element1, element2, ..., elementN).collect(Collectors.toCollection(ArrayList::new));

       1. Examples: 

Java
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class GFG {
    public static void main(String args[])
    {

        // create a stream of elements using Stream.of()
        // method collect the stream elements into an
        // ArrayList using the collect() method and
        // Collectors.toCollection() method
        ArrayList<String> list
            = Stream.of("Geeks", "For", "Geeks")
                  .collect(Collectors.toCollection(
                      ArrayList::new));

        System.out.println(list); // print the ArrayList
    }
}

Output
[Geeks, For, Geeks]


Similar Reads

Java.util.ArrayList.add() Method in Java
Below are the add() methods of ArrayList in Java: boolean add(Object o) : This method appends the specified element to the end of this list. Parameters: object o: The element to be appended to this list. Exception: NA // Java code to illustrate add(Object o) import java.io.*; import java.util.ArrayList; public class ArrayListDemo { public static vo
2 min read
Java.util.ArrayList.addall() method in Java
Below are the addAll() methods of ArrayList in Java: boolean addAll(Collection c) : This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. The behavior of this operation is undefined if the specified collection is modified while the ope
4 min read
Java.util.Arraylist.indexOf() in Java
The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Syntax : public int IndexOf(Object o) obj : The element to search for. // Java code to demonstrate the working of // indexOf in ArrayList // for ArrayList functions import java.util.Arra
2 min read
KeyPairGenerator initialize() method in Java with Examples
initialize(int keysize) The initialize() method of java.security.KeyPairGenerator is used to initialize KeyPairGenerator object for further use. Syntax: public void initialize(int keysize) Parameters: This method seeks keysize of int type as a parameter.Return Value: This method has nothing to return.Exception: This method throws InvalidParameterEx
3 min read
Initialize a static map in Java with Examples
In this article, a static map is created and initialized in Java. A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Method 1: Creating a static map variable. Instantiating it in a static block. Below is the implementation of the above approach: // Java program to creat
1 min read
Initialize a static Map using Stream in Java
In this article, a static map is created and initialized in Java using Stream. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Stream In Java Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of
2 min read
Initialize a static Map using Java 9 Map.of()
In this article, a static map is created and initialised in Java using Java 9. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Java 9 feature - Map.of() method In Java 9, Map.of() was introduced which is a convenient way to create instances of Map
2 min read
Initialize a static Map in Java using Double Brace Initialization
In this article, a static map is created and initialised in Java using Double Brace Initialization. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Double Brace Initialization In Double Brace Initialization: The first brace creates a new Anonymous
2 min read
Initialize a list in a single line with a specified value using Java Stream
Given a value N, the task is to create a List having this value N in a single line in Java using Stream. Examples: Input: N = 5 Output: [5] Input: N = GeeksForGeeks Output: [GeeksForGeeks] Approach: Get the value N Generate the Stream using generate() method Set the size of the List to be created as 1 using limit() method Pass the value to be mappe
2 min read
How to Initialize an Array in Java?
An array is a data structure in Java that is used to store data objects having the same data type. Each and every element in an array has a unique index value. In an array, we have to declare its size first and the size of the array is fixed. In an array, we can store elements of different data types like integer, string, date and etc. In this arti
5 min read
Initialize HashMap in Java
HashMap in Java is a part of the java.util package and allows storing key-value pairs. Initializing a HashMap can be done in multiple ways, including static blocks, utility methods from the Collections class, and modern approaches provided by Java 8 and Java 9. This article will guide you through these methods with clear examples and explanations.
4 min read
How to Initialize and Compare Strings in Java?
String is one of the most basic data types and it is widely used in storing and manipulating pieces of text. One of the fundamental features of strings in Java is their immutability that is once a string is created, it will never be changed. Immutability creates two general ways of initialization with strings in Java using the String Pool. This art
5 min read
Different Ways To Declare And Initialize 2-D Array in Java
An array with more than one dimension is known as a multi-dimensional array. The most commonly used multi-dimensional arrays are 2-D and 3-D arrays. We can say that any higher dimensional array is an array of arrays. A very common example of a 2D Array is Chess Board. A chessboard is a grid containing 64 1x1 square boxes. You can similarly visualiz
5 min read
ArrayList vs LinkedList in Java
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. However, the limitation of the array is that the size of the array is predefined and fixed. There are multiple ways to solve this problem. In this article, the difference between two classes that are implemented to
5 min read
Arraylist removeRange() in Java with examples
The removeRange() method of ArrayList in Java is used to remove all elements within the specified range from an ArrayList object. It shifts any succeeding elements to the left. This call shortens the list by (toIndex-fromIndex) elements where toIndex is the ending index and fromIndex is the starting index within which all elements are to be removed
3 min read
ArrayList get(index) Method in Java with Examples
The get() method of ArrayList in Java is used to get the element of a specified index within the list. Syntax: get(index) Parameter: Index of the elements to be returned. It is of data-type int. Return Type: The element at the specified index in the given list. Exception: It throws IndexOutOfBoundsException if the index is out of range (index=size(
2 min read
Arraylist lastIndexOf() in Java with example
The lastIndexOf() method of ArrayList in Java is used to get the index of the last occurrence of an element in an ArrayList object. Syntax : lastIndexOf(element) Parameter : The element whose last index is to be returned. Returns : It returns the last occurrence of the element passed in the parameter. It returns -1 if the element is not found. Prog
2 min read
Arraylist.contains() in Java
In Java, ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Syntax of Java ArrayList contains() :public boolean contains(Object) object-element to be searched for Parameters: object- element whose presence in this list is to be tested Returns: It returns true if the specified element i
2 min read
ArrayList trimToSize() in Java with example
The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list's current size. This method is used to trim an ArrayList instance to the number of elements it contains. Syntax: trimToSize() Parameter: It does not accepts any parameter. Return Value: It does not returns any value. It trims the capacity of this
1 min read
ArrayList isEmpty() in Java with example
The isEmpty() method of ArrayList in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element. Syntax: list_name.isEmpty() Parameter: It does not accepts any parameter. Returns: It returns True if the list list_name has no elements else it returns f
2 min read
ArrayList clear() Method in Java with Examples
The clear() method of ArrayList in Java is used to remove all the elements from a list. The list will be empty after this call returns so whenever this operation has been performed all elements of the corresponding ArrayList will be deleted so it does it becomes an essential function for deleting elements in ArrayList from memory leading to optimiz
2 min read
ArrayList retainAll() method in Java
The retainAll() method of ArrayList is used to remove all the array list's elements that are not contained in the specified collection or retains all matching elements in the current ArrayList instance that match all elements from the Collection list passed as a parameter to the method. Syntax: public boolean retainAll(Collection C) Parameters: The
4 min read
Array of ArrayList in Java
We often come across 2D arrays where most of the part in the array is empty. Since space is a huge problem, we try different things to reduce the space. One such solution is to use jagged array when we know the length of each row in the array, but the problem arises when we do not specifically know the length of each of the rows. Here we use ArrayL
2 min read
Reverse an ArrayList in Java using ListIterator
Assuming you have gone through arraylist in java and know about arraylist. This post contains different examples for reversing an arraylist which are given below:1. By writing our own function(Using additional space): reverseArrayList() method in RevArrayList class contains logic for reversing an arraylist with integer objects. This method takes an
6 min read
ArrayList spliterator() method in Java
The spliterator() method of ArrayList returns a Spliterator of the same elements as ArrayList but created Spliterator is late-binding and fail-fast. A late-binding Spliterator binds to the source of elements. It means that Arraylist at the point of the first traversal, first split, or the first query for estimated size, rather than at the time the
3 min read
ArrayList forEach() method in Java
The forEach() method of ArrayList used to perform the certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been Processed by the method or an exception is raised. The operation is performed in the order of iteration if that order is specified by the method. Exceptio
2 min read
ArrayList removeIf() method in Java
The removeIf() method of ArrayList is used to remove all of the elements of this ArrayList that satisfies a given predicate filter which is passed as a parameter to the method. Errors or runtime exceptions are thrown during iteration or by the predicate are pass to the caller. This method returns True, if we are able to remove some element. Java 8
3 min read
Java Program to Convert ArrayList to LinkedList
Given an array list, your task is to write a program to convert the given array list to Linked List in Java. Examples: Input: ArrayList: [Geeks, forGeeks, A computer Portal] Output: LinkedList: [Geeks, forGeeks, A computer Portal] Input: ArrayList: [1, 2, 3, 4, 5] Output: LinkedList: [1, 2, 3, 4, 5] ArrayList - An ArrayList is a part of the collect
6 min read
ArrayList iterator() method in Java with Examples
The iterator() method of ArrayList class in Java Collection Framework is used to get an iterator over the elements in this list in proper sequence. The returned iterator is fail-fast. Syntax: Iterator iterator() Parameter: This method do not accept any parameter. Return Value: This method returns an iterator over the elements in this list in proper
2 min read
ArrayList ensureCapacity() method in Java with Examples
The ensureCapacity() method of java.util.ArrayList class increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. Syntax: public void ensureCapacity(int minCapacity) Parameters: This method takes the desired minimum capacity as a parameter
2 min read
three90RightbarBannerImg