toArray ( ) method of List Interface in java.


Posted in : Core Java Posted on : January 13, 2011 at 7:22 PM Comments : [ 0 ]
Advertisements
In this section we will discuss about converting a list into array using toArray ( ) method of List interface in java.

toArray ( ) method of List Interface in java.

In this section we will discuss about converting a list into array using toArray ( ) method of List interface in java.

Syntax

public Object [] toArray ( )

This method returns entire elements of a list into an array in proper sequence from first to last.

In this method elements would be returned in the same chronological order in which it is gathered in the collection by its iterator. The returned array is free from any reference of collection. The returned array can be modified easily. Between the array based and collection based APIs this method works as bridge.

Parameter Description

This method does not take any argument but it returns an array.

Example of toArray ( ) method 

In this example we will show you how does toArray ( ) method works in List interface. This example will help you to understand how you can convert a list into an array? Through this example we will show you how list is converted into array, size of list, length of array.

Example:-

package Devmanuals.com;
import java.util.List;
import java.util.ArrayList;
public class ListToArray {
public static void main (String args []){
int size;
List ls=new ArrayList();
ls.add("a");
ls.add("b");
ls.add("c");
ls.add("d");
ls.add("e");
ls.add("f"); System.out.println("List is : "+ls);size= ls.size();
System.out.println("Size of list : "+size); Object[] obj=ls.toArray();System.out.println("Array = ");
for (int i = 0; i < obj.length; i++) {
System.out.println(obj[i]);
}
System.out.println("Length of array = "+obj.length); }}

Output :

List is : [a, b, c, d, e, f]

Size of list : 6

Array =

a

b

c

d

e

f

Length of array = 6

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Tutorial Topics