Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaJava Program to Change a Collection to an Array

Java Program to Change a Collection to an Array

An array is a data structure that can hold a fixed-size, homogeneous collection of elements of the same data type, which can be either primitive data types (e.g., int, float) or object references. However, the size of the array cannot be changed once it is created.

On the other hand, a collection is an interface in Java that defines a set of methods for storing and manipulating a group of objects. It can hold a variable number of elements of any type, including primitive types, but it can only hold objects, not primitive values. The actual implementation of a collection can be heterogeneous or homogeneous depending on the specific collection type used.

So, in summary, arrays can hold both homogeneous object and primitive data, but collections can only hold objects, not primitive values. And, collections can be heterogeneous or homogeneous, depending on the type of collection used. Following methods can be used to convert Collection to arrays:

  1. Using list.add() method
  2. Using list.toArray() method 

Approach 1: Using list.add() method
list.add() is used to insert the specified element E at the specified position in the list.

Syntax:

public void add(int index, E element);

Parameters:

  • 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.
Exception: 

Example:

Java




// Java program to change Collection to an array
 
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Arrays;
 
// Or simply add all generic lava libraries
import java.util.*;
 
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating arrayList list dynamically
        List<String> list = new ArrayList<String>();
        // List is created
 
        // Adding elements to the list
        list.add("Geeks ");
        list.add("for ");
        list.add("Geeks ");
        list.add("is ");
        list.add("the ");
        list.add("Best.");
 
        // Converting list to an array
        String[] str = list.toArray(new String[0]);
 
        // Iterating over elements of array
        for (int i = 0; i < str.length; i++) {
            String data = str[i];
 
            // Printing elements of an array
            System.out.print(data);
        }
    }
}


Output

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.

Syntax:

 public Object[] toArray() ;

Parameters:

  • 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:

Java




// Java program to convert Collections into Array
 
// Importing generic Java libraries
import java.util.*;
import java.io.*;
 
public class GFG {
 
    // Main driver code
    public static void main(String[] args)
    {
        // Reading input from the user
        // via BufferedReader class
        BufferedReader in = new BufferedReader(
            new InputStreamReader(System.in));
        // 'in' is object created of this class
 
        // Creating object of Scanner class
        Scanner sc = new Scanner(System.in);
 
        // Creating ArrayList to store user input
        List<String> list = new ArrayList<String>();
 
        // Taking input from user
        // adding elements to the list
        while (sc.hasNext()) {
            String i = sc.nextLine();
            list.add(i);
        }
 
        // Converting list to an array
        String[] str = list.toArray(new String[0]);
 
        // Iteration over array
        for (int i = 0; i < str.length; i++) {
            String data = str[i];
 
            // Printing the elements
            System.out.print(data);
        }
    }
}


 Output :

User Input : Geeks for Geeks
Output     : Geeks for Geeks

RELATED ARTICLES

Most Popular

Recent Comments