- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert an ArrayList to an Array with zero length Array in Java
An ArrayList can be converted into an Array using the java.util.ArrayList.toArray() method. This method takes a single parameter i.e. the array of the required type into which the ArrayList elements are stored and it returns an Array that contains all the elements of the ArrayList in the correct order.
A program that demonstrates this is given as follows −
Example
import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String[] args) { List<String> aList = new ArrayList<String>(); aList.add("James"); aList.add("Harry"); aList.add("Susan"); aList.add("Emma"); aList.add("Peter"); String[] arr = aList.toArray(new String[0]); System.out.println("The array elements are: "); for (String i : arr) { System.out.println(i); } } }
Output
The array elements are: James Harry Susan Emma Peter
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to this ArrayList. A code snippet which demonstrates this is as follows −
List<String> aList = new ArrayList<String>(); aList.add("James"); aList.add("Harry"); aList.add("Susan"); aList.add("Emma"); aList.add("Peter");
The method ArrayList.toArray() is used to convert the ArrayList into an Array. Then the Array elements are displayed using a for loop. A code snippet which demonstrates this is as follows −
String[] arr = aList.toArray(new String[0]); System.out.println("The array elements are: "); for (String i : arr) { System.out.println(i); }
- Related Articles
- How do you convert an ArrayList to an array in Java?
- Convert an ArrayList of String to a String array in Java
- How many ways are there to convert an Array to ArrayList in Java?
- How to create an ArrayList from an Array in Java?
- How to convert an object array to an integer array in Java?
- Convert LinkedList to an array in Java
- Convert an ArrayList to HashSet in Java
- Convert a Vector to an array in Java
- Copy all elements of ArrayList to an Object Array in Java
- Program to convert Stream to an Array in Java
- How to convert an array to string in java?
- Java program to convert an Array to Set
- How to convert an array of objects to an array of their primitive types in java?
- How to convert Java array or ArrayList to JsonArray using Gson in Java?
- How to convert an object to byte array in java?

Advertisements