Java Program to convert Array to ArrayList

Program

import java.util.Arrays;
import java.util.List;
public class ArrayToArrayList
{
    public static void main(String[] args)
    {
        String[] countryArray = {"India", "Australia", "France", "Germany"};
        System.out.println("From array:");
        for(int i = 0; i < countryArray.length; i++)
            System.out.println(countryArray[i]);
        System.out.println("From ArrayList:");
        List countryList = Arrays.asList(countryArray);
        System.out.println(countryList);
    }
}

This Java program demonstrates how to convert an Array to an ArrayList using the Arrays.asList() method.

  1. Import Statements:

    • The program imports java.util.Arrays and java.util.List to use utility classes for array and list operations.
  2. Creation of Array:

    • A String array named countryArray is initialized with four country names: "India", "Australia", "France", and "Germany".
  3. Displaying the Array:

    • A for loop iterates over the elements of the array, and each element is printed to the console.
  4. Conversion from Array to ArrayList:

    • The Arrays.asList(countryArray) method is used to convert the array into an ArrayList.
    • This creates a fixed-size list backed by the original array.
    • The resulting list is stored in the countryList variable.
  5. Displaying the ArrayList:

    • The ArrayList (countryList) is printed directly using System.out.println(countryList).

Output

From array:
India
Australia
France
Germany
From ArrayList:
[India, Australia, France, Germany]