Java Program to Change a Collection to an Array
The array is a linear data structure containing elements whose size is defined at the time of creation and can hold both object and primitive homogeneous data. The collection is a predefined class holding only heterogeneous object types but primitive. Method of java utility class can be used to change a collection to an array in java. Following methods can be used to convert Collection to arrays:
Approach 1: Using list.add() method
list.add() is used to insert the specified element E at the specified position in the list.
public void add(int index, E element);
- Index: The index where the element is to be inserted.
- Element: The element is to be inserted.
Return Value: This method does not return anything.
- IndexOutOfBoundsException: When the index is out of the range.
Geeks for Geeks is the Best
Approach 2: Using list.toArray() method
It is a method present there in the list interface that returns all the elements of the list in sequential order as an array.
public Object toArray() ;
- It is specified by ‘toArray’ in interface Collection and interface List
- It overrides ‘toArray’ in class Abstract Collection
- It returns an array containing all the elements in this list in the correct order.
Return Type: Value
An array of sequential elements of the list
Implementation: Below is an example of a clear understanding of the method and its usage:
User Input : Geeks for Geeks Output : Geeks for Geeks