ArrayList to Array in Java Example

(Last Updated On: August 11, 2016)

ArrayList to Array:
The below program converts ArrayList to Array.

Java Program:

package in.javadomain;

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

public class ArrayListTOArray {
	public static void main(String[] args) {
		List<String> mobilesList = new ArrayList<String>();
		mobilesList.add("Nokia");
		mobilesList.add("Karbonn");
		mobilesList.add("Micromax");
		mobilesList.add("Samsung");
		Object[] listToObj = mobilesList.toArray();
		String[] mobilesArray = Arrays.copyOf(listToObj, listToObj.length,
				String[].class);
		System.out.println("Value in Array is ::: " + mobilesArray[2]);

	}
}

Output:

Value in Array is ::: Micromax

Converting Object Array to String Array:

Object[] listToObj = mobilesList.toArray();
		String[] mobilesArray = Arrays.copyOf(listToObj, listToObj.length,
				String[].class);

Converting Integer ArrayList to Integer Array:

package in.javadomain;

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

public class ArrayListTOArray {
	public static void main(String[] args) {
		List<Integer> mobilesList = new ArrayList<Integer>();
		mobilesList.add(1);
		mobilesList.add(2);
		mobilesList.add(3);
		mobilesList.add(4);
		Object[] listToObj = mobilesList.toArray();
		Integer[] mobilesArray = Arrays.copyOf(listToObj, listToObj.length,
				Integer[].class);
		System.out.println("Value in Array is ::: " + mobilesArray[2]);
	}
}

Output:
Value in Array is ::: 3

Converting Integer Object to Integer:

Object[] listToObj = mobilesList.toArray();
		Integer[] mobilesArray = Arrays.copyOf(listToObj, listToObj.length,
				Integer[].class);

158 total views, 1 views today

Leave a Reply

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