List toArray() Method

      No Comments on List toArray() Method




java.util.List.toArray() method can be used to convert a list to an array.

Syntax of List toArray() Method

Object[] java.util.List.toArray()

The return type of this method is Object[].

Example.java

The below program demonstrates how to use toArray() method on a list object.

package com.masterjavatutorial;

import java.util.ArrayList;
import java.util.List;

public class Example {

	public static void main(String[] args) {
      
		List list = new ArrayList();
		list.add("Delhi");
		list.add("Mumbai");
		list.add("Bangalore");
		list.add("Kolkatta");
		list.add("Patna");
		list.add("Lucknow");
		
		Object[] array = list.toArray(); 
		for(Object obj : array){
                   //typecasting of each array object
                   String str = (String)obj;
		   System.out.println(str);
		}
		
	}

}

Output of the above program is as below:

Delhi
Mumbai
Bangalore
Kolkatta
Patna
Lucknow

toArray() method returns array object containing elements in the same order as that of the list insertion order.