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.
 */
packagecom.allinalljava;
// Convert an ArrayList into an array.
importjava.util.*;
classArrayListToArray {

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

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);
}
}


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

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...