Horje
How to Declare an ArrayList with Values in Java?

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

//Java program to declare an ArrayList with values 
//importing util package to use the methods 
import java.util.*;
  
public class GFG {
    public static void main(String[] args) {
          
        // Declare and initialize ArrayList using Arrays.asList
        ArrayList<Integer> arrayList = new ArrayList<>();
  
    //Adding Values to the ArrayList
    arrayList.add(5);
    arrayList.add(1);
    arrayList.add(2);
    arrayList.add(4);
      
  
  
        // Print ArrayList
        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.



Reffered: https://www.geeksforgeeks.org


Java

Related
Implement a Sparse Matrix Representation and Operations in Java Implement a Sparse Matrix Representation and Operations in Java
Java Program to Create a File with a Unique Name Java Program to Create a File with a Unique Name
How to Evaluate Math Expression Given in String Form in Java? How to Evaluate Math Expression Given in String Form in Java?
How to Split an ArrayList in Multiple Small ArrayLists? How to Split an ArrayList in Multiple Small ArrayLists?
How to Iterate Over a HashSet Without an Iterator in Java? How to Iterate Over a HashSet Without an Iterator in Java?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13