How to Convert an ArrayList Containing Integers to Primitive Int Array?
Last Updated :
09 Feb, 2024
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
import java.util.ArrayList;
public class GFGexample
{
public static void main(String[] args)
{
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add( 10 );
arrayList.add( 50 );
arrayList.add( 100 );
arrayList.add( 150 );
int [] intArray = convertToIntArray(arrayList);
System.out.print( "Original ArrayList: " + arrayList);
System.out.println( "\nConverted int array: " + java.util.Arrays.toString(intArray));
}
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.
Share your thoughts in the comments
Please Login to comment...