How to Creating arraylist from array in java? | Projectshop


Sure, here’s how you can create an ArrayList from an array in Java:

Java
import java.util.ArrayList;
import java.util.Arrays;

public class ArrayToArrayList {
    public static void main(String[] args) {
        // Create an array
        String[] array = {"apple", "banana", "orange"};

        // Convert array to ArrayList
        ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(array));

        // Print the ArrayList
        System.out.println("ArrayList: " + arrayList);
    }
}

Explanation:

  1. First, import the required classes: ‘ArrayList‘ from ‘java.util‘ and ‘Arrays‘.
  2. Create an array of strings ‘array‘ with some elements.
  3. Use ‘Arrays.asList(array)‘ to convert the array to a List.
  4. Pass this list as an argument to the ‘ArrayList‘ constructor, which creates a new ArrayList containing the elements of the list.
  5. Now, you have an ArrayList ‘arrayList‘ containing the elements of the original array.
  6. Finally, print out the ArrayList to see its contents.

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart