1. Introduction
Converting an Array to a List in Java can be useful when you need functionalities provided by the List interface, such as adding, removing, or checking the existence of elements. Java provides a convenient Arrays.asList() method that can be used to convert an Array into a fixed-size List.
2. Program Steps
1. Initialize an Array with some elements.
2. Convert the Array to a List using the Arrays.asList() method.
3. Print the original Array and the converted List.
3. Code Program
import java.util.List;
import java.util.Arrays;
public class ArrayToList {
public static void main(String[] args) {
// Step 1: Initialize an Array with some elements
String[] fruitArray = {"Apple", "Banana", "Cherry"};
// Step 2: Convert the Array to a List using the Arrays.asList() method
List<String> fruitList = Arrays.asList(fruitArray);
// Step 3: Print the original Array and the converted List
System.out.println("Original Array: " + Arrays.toString(fruitArray));
System.out.println("Converted List: " + fruitList);
}
}
Output:
Original Array: [Apple, Banana, Cherry] Converted List: [Apple, Banana, Cherry]
4. Step By Step Explanation
Step 1: We initialize an Array named fruitArray with some elements.
Step 2: We use the Arrays.asList() method to convert fruitArray into a List named fruitList. The Arrays.asList() method returns a fixed-size list backed by the specified array.
Step 3: Finally, we print the original fruitArray and the fruitList to the console. The Arrays.toString() method is used to print the array elements.
Note that the List returned from Arrays.asList() is backed by the original array. Any structural modification to the List (such as adding or removing elements) will throw an UnsupportedOperationException.