Convert ArrayList to Array in Java

In this tutorial you will learn how to convert ArrayList to Array in Java.

Mainly there are two ways to convert ArrayList to array.

  • Using manual way
  • Using toArray() method

Below I have share an example for both the ways.

Convert ArrayList to Array in Java

How to Convert ArrayList to Array in Java

Convert Using Manual Way

In this method we will first create an array of size equal to ArrayList size. After that fetch each element of ArrayList using get() method and then copy it into array.

package com;

import java.util.ArrayList;

public class ArrayListToArray {
	public static void main(String args[]){
		ArrayList<String> list=new ArrayList<String>();
		
		//Adding few elements in ArrayList
		list.add("C");
		list.add("C++");
		list.add("Java");
		list.add("Android");
		
		String str[]=new String[list.size()];
		
		//converting ArrayList to String Array
		for(int i=0;i<list.size();++i){
			str[i]=list.get(i);
		}
		
		//printing the converted String Array
		for(int i=0;i<str.length;++i){
			System.out.println(str[i]+" ");
		}
	}
}

 

Output

C
C++
Java
Android

 

Convert Using toArray() Method

ArrayList class provides a method toArray() which directly converts an ArrayList to Array. It can be done in following way.

package com;

import java.util.ArrayList;

public class ArrayListToArray {
	public static void main(String args[]){
		ArrayList<String> list=new ArrayList<String>();
		
		//Adding few elements in ArrayList
		list.add("C");
		list.add("C++");
		list.add("Java");
		list.add("Android");
		
		String str[]=new String[list.size()];
		
		//converting ArrayList to String Array
		str=list.toArray(str);
		
		//printing the converted String Array
		for(int i=0;i<str.length;++i){
			System.out.println(str[i]+" ");
		}
	}
}

 

Output

C
C++
Java
Android

 

These were the simple ways to convert ArrayList to Array in Java. Comment below if you found anything incorrect or have doubts related to above tutorial.

1 thought on “Convert ArrayList to Array in Java”

  1. What is the point of this article? Calling “toArray” is obviously superior.
    Also, why are you using a for loop? to walk the ArrayList? Use list.stream().forEach(item -> { … } or for (item: list) { … }.

Leave a Comment

Your email address will not be published. Required fields are marked *