Convert ArrayList to Array in Java
In this tutorial, you will figure out how to convert ArrayList to Array in Java.
Mainly there are two different ways to convert ArrayList to the array.
- Using the manual way
- Using toArray() technique
Beneath I have shared an example for both the ways.
Step by step instructions to Convert ArrayList to Array in Java
Convert Using Manual Way
In this technique, we will initially make an array of a size equivalent to ArrayList size.
After that get every component of ArrayList using get() strategy and afterwards duplicate it into an 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 gives a strategy toArray() which straightforwardly converts an ArrayList to Array.
It very well may be done in the following manner.
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 basic approaches to convert ArrayList to Array in Java. Remark beneath in the event
that you discovered anything incorrect or have questions identified with the above tutorial.