- 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
Copy all elements of ArrayList to an Object Array in Java
All the elements of an ArrayList can be copied into an Object Array using the method java.util.ArrayList.toArray(). This method does not have any parameters and it returns an Object Array that contains all the elements of the ArrayList copied 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("Nathan"); aList.add("John"); aList.add("Susan"); aList.add("Betty"); aList.add("Peter"); Object[] objArr = aList.toArray(); System.out.println("The array elements are: "); for (Object i : objArr) { System.out.println(i); } } }
Output
The array elements are: Nathan John Susan Betty 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("Nathan"); aList.add("John"); aList.add("Susan"); aList.add("Betty"); aList.add("Peter");
The method ArrayList.toArray() is used to copy all the elements of the ArrayList into an Object Array. Then the Object Array elements are displayed using a for loop. A code snippet which demonstrates this is as follows −
Object[] objArr = aList.toArray(); System.out.println("The array elements are: "); for (Object i : objArr) { System.out.println(i); }
Advertisements