Skip to main content

25. T[] toArray(T[] a)

25. T[] toArray(T[] a)
Returns an array containing all of the elements in this list in proper sequence (from first to last element);
the runtime type of the returned array is that of the specified array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.spy.arraylist.method;
 
import java.util.ArrayList;
 
public class Toarray 
{
 
	public static void main(String[] args) 
	{
 
 
		 ArrayList<String> emp_list=new ArrayList<>();
 
			emp_list.add("Bhavesh Lakhani");
			emp_list.add("Abhilash Shah");
			emp_list.add("Nilay Shah");
			emp_list.add("Vaibhav Prajapati");
 
			System.out.println("Retrieving element of Arraylist......");
 
			for (String s : emp_list) 
			{
				 System.out.println(s);
 
			}
 
			String[] s=new String[emp_list.size()];
 
			//toarray copies element into another Array
	         s=emp_list.toArray(s);
 
			System.out.println("Retrieving element of Array......");
 
			for(int i=0;i<s.length;i++)
			{
 
				System.out.println(s[i]);
			}
	  }
}

Output:

1
2
3
4
5
6
7
8
9
10
11
 
Retrieving element of Arraylist......
Bhavesh Lakhani
Abhilash Shah
Nilay Shah
Vaibhav Prajapati
Retrieving element of Array......
Bhavesh Lakhani
Abhilash Shah
Nilay Shah
Vaibhav Prajapati