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.
-
Import Statements:
- The program imports
java.util.Arrays
andjava.util.List
to use utility classes for array and list operations.
- The program imports
-
Creation of Array:
- A
String
array namedcountryArray
is initialized with four country names: "India", "Australia", "France", and "Germany".
- A
-
Displaying the Array:
- A
for
loop iterates over the elements of the array, and each element is printed to the console.
- A
-
Conversion from Array to ArrayList:
- The
Arrays.asList(countryArray)
method is used to convert the array into anArrayList
. - This creates a fixed-size list backed by the original array.
- The resulting list is stored in the
countryList
variable.
- The
-
Displaying the ArrayList:
- The
ArrayList
(countryList
) is printed directly usingSystem.out.println(countryList)
.
- The
Output
From array:
India
Australia
France
Germany
From ArrayList:
[India, Australia, France, Germany]