Filled Under: Array, Collections Framework
How To Obtain Int Array from Array List
Before reading this tutorial you must have knowledge regarding basics of array list see tutorial on array list .To perform any operation on array list first it should be converted into an array of desired data in this example we are converting arraylist to int array to perform simple addition to this we have use two different method first is toArray which convert arraylist to array then we we use intValue to convert it into int array.
CODING:
import java.util.*;
class arraylisttoarray
{
public static void main(String args[])
{
ArrayList a1 = new ArrayList();
a1.add(1);
a1.add(2);
a1.add(2);
System.out.println("Initial size of a1:"+a1.size());
Object a[]=a1.toArray();
int sum=0;
for(int i=0;i<a.length;i++)
sum +=((Integer) a[i]).intValue();
System.out.println(sum);
}
}
OUTPUT:
This comment has been removed by a blog administrator.
ReplyDelete