How to Declare an ArrayList with Values in Java?
Last Updated :
01 Feb, 2024
ArrayList is simply known as a resizable array. Declaring an ArrayList with values is a basic task that involves the initialization of a list with specific elements. It is said to be dynamic as the size of it can be changed. Proceeding with the declaration of ArrayList, we have to be aware of the concepts of Arrays and Lists in Java programming.
In this article, we will learn to declare an ArrayList with values in Java.
Program to declare an ArrayList with Values
It is the easiest and most direct method to add values while declaration. There is a basic way to declare an ArrayList with values is by Adding elements one by one by using the add() method.
Syntax:
ArrayList<Integer> arrayList = new ArrayList<>();arrayList.add(1);arrayList.add(2);
Below is the implementation of Declare an ArrayList with Values in Java:
Java
import java.util.*;
public class GFG {
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add( 5 );
arrayList.add( 1 );
arrayList.add( 2 );
arrayList.add( 4 );
System.out.println( "ArrayList: " + arrayList);
}
}
|
Output
ArrayList: [5, 1, 2, 4]
Explanation of the above Program:
- In the above example, from the java.util package we have imported the ArrayList class.
- Then, we have declared an ArrayList with the name arrayList and it stores the integer objects.
- After that we have used the add() method to add elements to ArrayList.
- At last, it prints all the values to an ArrayList.
Share your thoughts in the comments
Please Login to comment...