

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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); }
- Related Questions & Answers
- Copy all elements of Java HashSet to an Object Array
- Copy all elements of Java LinkedHashSet to an Object Array
- Copy all elements in Java TreeSet to an Object Array
- How to copy elements of ArrayList to Java Vector
- Copy Elements of One ArrayList to Another ArrayList with Java Collections Class
- How to remove all elements of ArrayList in Java?
- Append all elements of other Collection to ArrayList in Java
- How to remove the redundant elements from an ArrayList object in java?
- Python program to copy all elements of one array into another array
- Replace All Elements Of ArrayList with with Java Collections
- Java Program to append all elements of other Collection to ArrayList
- Reverse order of all elements of ArrayList with Java Collections
- Remove all elements from the ArrayList in Java
- Create an object array from elements of LinkedList in Java
- Sort Elements in an ArrayList in Java
Advertisements