Convert list into array list

How to convert a Java list to an array

In Java, there are many situations where a list has to be converted to an array [e.g., a function that only accepts an array as a parameter instead of a collection]. This conversion is done using the toArray[] method of the List interface.

There are two variants of this method:

1. toArray[]

This method returns an array of type Object[] whose elements are all in the same sequence as they are in the list. Casting is used to specify each elements type when performing some operations.

Code

import java.util.ArrayList; public class ListToArray { public static void main[String[] args] { // A list of size 4 which is to be converted: ArrayList list = new ArrayList[]; list.add[1]; list.add[2]; list.add[3]; list.add[4]; // ArrayList converted to Object[] array: Object[] objArr = list.toArray[]; for[Object obj: objArr]{ // Using casting before performing addition: System.out.println[[Integer]obj + 1]; } } }
Run

2. toArray[T[] arr]

This variant of the same method takes an already defined array as its parameter. When ​the arrays size is greater than or equal to the size of the list, then the array is filled with the elements of the list. Otherwise, a new array will be created and filled up. Since the type of the returned array is specified by the parameters type, casting is unnecessary. However, ArrayStoreException is thrown if any element in the list fails to be​ converted into the specified type.

Code

import java.util.ArrayList; public class ListToArray { public static void main[String[] args] { // A list of size 4 to be converted: ArrayList list = new ArrayList[]; list.add[2]; list.add[3]; list.add[4]; list.add[5]; // Declaring an array of size 4: Integer[] arr = new Integer[4]; // Passing the declared array as the parameter: list.toArray[arr]; // Printing all elements of the array: System.out.println["Printing 'arr':"]; for[Integer i: arr] System.out.println[i]; // Declaring another array of insufficient size: Integer[] arr2 = new Integer[3]; // Passing the array as the parameter: Integer[] arr3 = list.toArray[arr2]; // Printing the passed array: System.out.println["\n'arr2' isn't filled because it is small in size:"]; for[Integer i: arr2] System.out.println[i]; // Printing the newly allocated array: System.out.println["\n'arr3' references the newly allocated array:"]; for[Integer i: arr3] System.out.println[i]; } }
Run

Video liên quan

Chủ Đề