Convert an ArrayList into an Array

In following program you can   easily convert ArrayList  in to an array. The program starts by means of creating a collection of integers. Then, toArray( ) is called and it Collects an array of Integers. Next the contents of that array are summed by use of a for-each style for loop.The capacity of arraylist grows automatically as elements are added .
// Comment
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
// Convert an ArrayList into an array.
classArrayListToArray {

public static void main(String args[]) {
// Create an array list.
ArrayListarrayList = new ArrayList();
// Add elements to the array list.

System.out.println(" The Data in Array List is" + arrayList);
// Get the array.
Integer array[] = new Integer[arrayList.size()];
array = arrayList.toArray(array);
int sum = 0;
// Sum the array.
for(int i : array) sum += i;
System.out.println("Sum is: " + sum);

The Data in Array List is[1, 2, 3, 4] Sum is: 10
test Web Developer

No comments:

Post a comment

Related Posts Plugin for WordPress, Blogger...