Obtaining an Array from an ArrayList

Obtaining an Array from an ArrayList

While working with ArrayList we come to  a situation where we need actual array from arrayList.  Several reasons exist why we might want to convert a collection into an array such as…

  1. To integrate our collection based code to legacy code which doesn’t understand collection framework.
  2. To use a utility method which accept only array as parameter.
  3. To obtain faster processing times for certain operations.

Sample code 1

package com.code2succeed.collection;

import java.util.ArrayList;
import java.util.List;

public class ConvertArrayListToArray {
	public static void main(String[] args) {
		//Create list without generic.
                List al = new ArrayList();
		al.add(1);
		al.add(2);
		al.add(3);
		al.add(4);
		
		//display content of ArrayList
		System.out.println("Content of arrayList : "+al);
		
		//get array
		Object [] array = al.toArray();
		// sum the array 
		int sum = 0;
		for(int i=0; i<array.length; i++) { 
			sum += ((Integer) array[i]).intValue();
		}
		System.out.println("Sum : "+sum);
	}
}

Output

Content of arrayList : [1, 2, 3, 4]
Sum : 10

Sample code 2.

package com.code2succeed.collection;

import java.util.ArrayList;
import java.util.List;

public class ConvertArrayListToArray {
	public static void main(String[] args) {
		//Create List using generic.
                List<Integer> al = new ArrayList<Integer>();
		al.add(1);
		al.add(2);
		al.add(3);
		al.add(4);
		
		//display content of ArrayList
		System.out.println("Content of arrayList : "+al);
		
		//get array
		Integer [] array = al.toArray(new Integer[al.size()]);
		// sum the array 
		int sum = 0;
		for(int i=0; i<array.length; i++) { 
			sum += array[i].intValue();
		}
		System.out.println("Sum : "+sum);
	}
}

Output

Content of arrayList : [1, 2, 3, 4]
Sum : 10

Leave a Reply

Your email address will not be published. Required fields are marked *