Open In App

How to Convert an ArrayList Containing Integers to Primitive Int Array?

Last Updated : 09 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, ArrayList is the pre-defined class of the Java Collection Framework. It is part of the java.util package. ArrayList can be used to add or remove an element dynamically in the Java program. It can be snipped dynamically based on the elements added or removed into the ArrayList.

In this article, we will discuss how to convert an ArrayList containing Integers to a primitive int array.

Methods to Convert an ArrayList containing Integers to Primitive Int Array

Two methods are mostly used to implement the ArrayList integers convert into a primitive integer array.

  • add(): It is a pre-defined method of the ArrayList that can be used to add the elements into the ArrayList.
  • get(): it is also an in-built method and it can be used to retrieve the elements into the ArrayList.

Program to Convert an ArrayList Containing Integers to Primitive Int Array in Java

Java




// Java Program to convert an ArrayList
// Containing Integers to primitive int array
import java.util.ArrayList;
  
//ArrayList convert into the primitive int array
public class GFGexample 
{
    //main method
    public static void main(String[] args) 
    {
        // Create the ArrayList named as arrayList
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(10);
        arrayList.add(50);
        arrayList.add(100);
        arrayList.add(150);
  
        // Convert ArrayList<Integer> to int[]
        int[] intArray = convertToIntArray(arrayList);
  
        // print the result
        System.out.print("Original ArrayList: " + arrayList);
        System.out.println("\nConverted int array: " + java.util.Arrays.toString(intArray));
    }
  
    // method to convert ArrayList<Integer> to int[]
    private static int[] convertToIntArray(ArrayList<Integer> list) 
    {
        int[] intArray = new int[list.size()];
          
        for (int i = 0; i < list.size(); i++) 
        {
            intArray[i] = list.get(i);
        }
  
        return intArray;
    }
}


Output

Original ArrayList: [10, 50, 100, 150]
Converted int array: [10, 50, 100, 150]

Explanation of the Program:

  • The above program is the example of the ArrayList can be convert into primitive integer array that Integer is the wrapper class that values can be convert into the normal primitive integer values into the program.
  • It can be implemented first we have to create one Integer ArrayList then add the integer values into the ArrayList after that we can convert the ArrayList into the primitive integer.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads