- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to change a collection to an array using Java
Problem Description
How to change a collection to an array?
Solution
Following example shows how to convert a collection to an array by using list.add() and list.toArray() method of Java Util class.
import java.util.*;
public class CollectionToArray{
public static void main(String[] args){
List<String> list = new ArrayList<String>();
list.add("This ");
list.add("is ");
list.add("a ");
list.add("good ");
list.add("program.");
String[] s1 = list.toArray(new String[0]);
for(int i = 0; i< s1.length; ++i) {
String contents = s1[i];
System.out.print(contents);
}
}
}
Result
The above code sample will produce the following result.
This is a good program.
java_collections.htm
Advertisements