In this section we will discuss about converting a list into an array using toArray (Object [ ] a ) method of List interface in java.
toArray (Object [ ] a) method of List Interface in java.
In this section we will discuss about converting a list into an array using toArray (Object [ ] a ) method of List interface in java.
Syntax
public Object [ ] toArray (Object [ ] a)
This method returns entire elements of a list into an array in proper sequence from first to last.
toArray (Object[ ] a ) method returns the element in the same sequence of a list and in the same runtime type that is specified during input. The returned array is free from any reference.
Parameter Description
Object [ ] a : This parameter stores the list containing all the elements in the same manner and runtime type if it is big enough otherwise it allocate a new array of the same runtime type for the storage.
Example of toArray (Object [ ] a ) method
In this example we will show you how does toArray (Object [ ] a ) method work in List interface. This example will help you to understand how you can find the runtime type of the returned array in the specified array. Through this example we will show you the procedure of conversing a same runtime type list into an specified array.
Example:-
package Devmanuals.com; import java.util.List; import java.util.ArrayList; public class ListToArrayObject { public static void main(String args []){ List<Integer> ls=new ArrayList(); ls.add(4); ls.add(5); Integer elements[] = {1,2,3}; System.out.println("element old: "); for (int i =0; i<elements.length;i++) { System.out.println(elements[i]); } System.out.println(" "); System.out.println("New element: "); for (int i =0; i<ls.size();i++) { System.out.println(ls.get(i)); } Integer a[] = new Integer[ls.size()]; a= ls.toArray(elements); System.out.println("New array = "); for (int i =0; i<a.length;i++) System.out.println(a[i]); System.out.println("Length of an array : "+a.length); } }
Output :
element old: 1 2 3 New element: 4 5 New array = 4 5 null Length of an array : 3 |
[ 0 ] Comments