Clean Java

There is always a bigger game

Array to Collection and Collection to Array Convertion in java.

leave a comment »


package org.sanju.collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

/**
 * @author sanju.org
 * @date 31st July, 2011
 * 
 * How to convert a collection to array 
 * How to convert an array to Collection
 * How to convert a list to array
 * How to convert an array to list
 *
 */

public class CollectionToArrayExample {

	public static void main(String args[]){
		
		Collection list = new ArrayList();
		
		for(int i = 0; i<10; i++){
			list.add(Math.random());
		}
		
		//collection to array
		Double [] doubles = (Double[])list.toArray(new Double[list.size()]);
		
		for(Double d : doubles){
			System.out.println(d);
		}
		
		//array to collection
		Collection collection = Arrays.asList(doubles);
		
		for(Double cd : collection){
			System.out.println(cd);
		}
	}
	
}

Advertisements

Written by cleanjava

August 1, 2011 at 10:11 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: