The Collection interface includes the toArray() method to
convert a new collection into an array. There are two forms of this method. The
no argument version will return the elements of the collection in an Object
array: public Object[ ] toArray().
The returned array cannot cast to any other data type. This is the simplest
version. The second version requires you to pass in the data type of the array
you’d like to return: public Object [ ]
toArray(Object type[ ]).
For example:- assume col represents a collection of Date
objects,
Date d[ ] = (Date []) col.toArray(new Date[0]);
To convert ArrayList into an Array, first method is
sufficient.
Sample Program:-
import java.util.ArrayList;
import java.util.List;
public class ConvertArrayListIntoArray {
/**
* @param args
*/
public static void main(String[] args) {
List<String> l=new ArrayList<String>();
l.add("A");
l.add("B");
l.add("C");
Object arr[]=l.toArray();
for(Object a:arr)
{
String str=(String)a;
System.out.println(str);
}
}
}
Output:-
A
B
C
Enjoy Reading
No comments:
Post a Comment