- 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
Java program to convert a list to an array
The List object provides a method known as toArray(). This method accepts an empty array as argument, converts the current list to an array and places in the given array. To convert a List object to an array −
- Create a List object.
- Add elements to it.
- Create an empty array with size of the created ArrayList.
- Convert the list to an array using the toArray() method, bypassing the above-created array as an argument to it.
- Print the contents of the array.
Example
import java.util.ArrayList; public class ListToArray { public static void main(String args[]){ ArrayList<String> list = new ArrayList<String>(); list.add("Apple"); list.add("Orange"); list.add("Banana"); System.out.println("Contents of list ::"+list); String[] myArray = new String[list.size()]; list.toArray(myArray); for(int i=0; i<myArray.length; i++){ System.out.println("Element at the index "+i+" is ::"+myArray[i]); } } }
Output
Contents of list ::[Apple, Orange, Banana] Element at the index 0 is ::Apple Element at the index 1 is ::Orange Element at the index 2 is ::Banana
- Related Articles
- Java program to convert an array to a list
- How to convert an Array to a List in Java Program?
- Program to convert Array to List in Java
- How to convert an array to a list in Java?
- Java program to convert a Set to an array
- Golang Program to Convert Linked list to an Array
- Can we convert a list to an Array in Java?
- Java program to convert an Array to Set
- Java Program to convert a set into an Array
- Program to convert Stream to an Array in Java
- Write a program to convert an array to String in Java?
- convert list to array in java
- How to convert a list to array in Java?
- Java Program to convert a list to a read-only list
- Can we convert a Java array to list?

Advertisements