- 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); }
Advertisements
To Continue Learning Please Login
Login with Google