w3resource

Java: Convert an array to ArrayList


Write a Java program to convert an array to an ArrayList.

Pictorial Presentation:

Java Array Exercises:  Convert an array to ArrayList

Sample Solution:

Java Code :

// Import the ArrayList and Arrays classes from the Java utility library.
import java.util.ArrayList;
import java.util.Arrays;

// Define a class named Exercise20.
public class Exercise20 {
    public static void main(String[] args) {
        // Create an array of strings.
        String[] my_array = new String[] {"Python", "JAVA", "PHP", "Perl", "C#", "C++"};

        // Create an ArrayList of strings and initialize it with the contents of the array.
        ArrayList list = new ArrayList(Arrays.asList(my_array));

        // Print the ArrayList to the console.
        System.out.println(list);
    }
}

Sample Output:

[Python, JAVA, PHP, Perl, C#, C++] 

Flowchart:

Flowchart: Java exercises: Convert an array to ArrayList

For more Practice: Solve these Related Problems:

  • Write a Java program to convert an ArrayList back to an array.
  • Write a Java program to convert an array of primitive data types into an ArrayList.
  • Write a Java program to remove duplicate elements while converting an array to an ArrayList.
  • Write a Java program to convert a multi-dimensional array into a list of lists.

Java Code Editor:

Previous: Write a Java program to add two matrices of the same size.
Next: Write a Java program to convert an ArrayList to an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.