Monday, January 16, 2012

Converting an ArrayList into an array.


//Obtaining an Array from an ArrayList

import java.util.*;
class ArrayListToArray
{
public static void main(String args[])
{
// Create an array list
ArrayList<Integer> al = new ArrayList<Integer>();

// Add elements to the array list
al.add(new Integer(1));
al.add(new Integer(2));
al.add(new Integer(3));
al.add(new Integer(4));
System.out.println("Contents of al: " + al);

// get array
Object ia[] = al.toArray();
int sum = 0;

//Display using array
System.out.println("Display using array");
for(int i=0;i<ia.length;i++)
{
System.out.println(ia[i]);
}

// sum the array
for(int i=0; i<ia.length; i++)
sum += ((Integer) ia[i]).intValue();
System.out.println("Sum is: " + sum);
}
}

Output:

Contents of al: [1, 2, 3, 4]
Display using array
1
2
3
4
Sum is: 10


Note:
Reasons to convert ArrayList to Array:
  • To obtain faster processing times for certain operations.
  • To pass an array to a method that is not overloaded to accept a collection.
  • To integrate collection-based code with legacy code that does not understand collections.

No comments:

Post a Comment