The java.util.ArrayList.toArray(T[]) returns an array containing all the items in this list in natural order (from the first to the last element).
ArrayList t = new ArrayList();
t.add(1);
t.add(10.5f);
t.add("qlq ch");
//get array
Object[] obj = t.toArray();
Create an array with a generic type
In the previous example, our ArrayList containing objects of different types: int, string, double. There are case where the array contains a single type and when you convert it you get an array of objects. In order for these objects to be usable, they are also converted to the desired type but, be careful! Conversion is done according to genericity in ArrayList< T>.
ArrayListt = new ArrayList ();
t.add(34);
t.add(10);
t.add(54);
Object[] obj = t.toArray();
int[] obj_int = new int[obj.length];
for(int i=0; i < obj_int.length; i++)
//Convert objects to int
obj_int[i]=(int) obj[i];
Convert ArrayList< Table> in a matrix
This code shows the case of a list within another list. There are other cases List< Object[]> or List< List< List<... > > > . The example List< list> is the most used:
ArrayListReferences:tm = new ArrayList ();
//populate the list
for(int i=0; i < list.size(); i++){
ArrayList al = new ArrayList();
for(int i1=0; i1 < list.size(); i1++)
//generate random numbers
al.add(Math.random());
tm.add(al);
}
Object[][] mt = new Object[tm.size()][tm.get(0).size()];
for(int i = 0 ; i < tm.size(); i++)
//copy the values into each row of the array
mt[i] = tm.get(i).toArray();
//display
for(int i=0; i < mt[0].length; i++){
for(int j=0; j < mt[0].length; j++)
System.out.print(mt[i][j]+" ");
System.out.println(" ");
}
Java.util.ArrayList.toArray(T[]) Method
Convert list to array in Java
Commentaires (12)
Connectez-vous pour commenter
Rejoignez la discussion et partagez vos connaissances avec la communauté
Excellent tutoriel !
N'hésitez pas si vous avez des questions.