In the previous article, we have seen Java Program to Convert an Array to Array-List
In this article we are going to see how we can convert an ArrayList into an Array in Java.
Java Program to Convert an Array-List to Array
Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.
In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.
Declaration of an array:
dataType[] arrayName; (or) //Declaring an array dataType []arrayName; (or) dataType arr[];
Instantiation of an Array:
arrayName = new datatype[size]; //Allocating memory to array
Combining both Statements in One:
dataType[] arrayName = new dataType[size] //Declaring and Instantiating array
Initialization of an Array:
arrayName[index-0]= arrayElement1 //Initializing the array ... arrayName[index-s]= arrayElementS
Combining all Statements in One:
dataType arrayName[ ]={e1,e2,e3}; //declaration, instantiation and initialization
Let’s see different ways how to convert an ArrayList into an Array.
Method-1: Java Program to Convert an Array-List to Array By Using toArray( ) function
Approach:
- Create an arraylist.
- Display the arraylist to the user.
- Convert the arraylist into array by using
toArray()
function. - Display the array.
Program:
import java.util.*; public class Main { public static void main(String args[]) { // Creating an arraylist ArrayList<String> arrlist = new ArrayList<String>(); // Adding elements to arraylist arrlist.add("Mango"); arrlist.add("Apple"); arrlist.add("Papaya"); // Displaying the arraylist System.out.println("ArrayList: " + arrlist); // Creating the array and converting arraylist to array String[] arr = arrlist.toArray(new String[0]); // Displaying the array to the user System.out.print("Array: "); printArray(arr); } // Function to print the array static void printArray(String arr[]) { for(int i = 0; i < arr.length ; i++) System.out.print(arr[i]+" "); System.out.println(); } }
Output: ArrayList: [Mango, Apple, Papaya] Array: Mango Apple Papaya
Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.
Related Java Programs: