24. Object[] toArray()


Returns an array containing all of the elements in this list in proper sequence (from first to last element).

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 CovertingToArray 
{
 
	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);
 
		}
 
		// Converting Arraylist collection  to Array
		Object[] emp_name=(Object[]) emp_list.toArray();
 
		System.out.println("Retrieving element of Array......");
 
		for(int i=0;i<emp_name.length;i++)
		{
 
			System.out.println(emp_name[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

Leave a Reply

Your email address will not be published. Required fields are marked *