
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Convert List to Array in Java
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
Advertisements