Convert Array to ArrayList

JavaJavaBeginner
Practice Now

Introduction

In Java, an array is used to store similar types of elements, while an ArrayList is an implementation class of the List interface used to store elements index-based. There may be instances when you need to convert an array to an ArrayList when working with collections of data. This lab will teach you how to convert an array to ArrayList in Java.

Create an array of elements

In this step, create an array of elements, for example, a String array.

String[] fruits = {"Apple", "Orange", "Banana"};

Convert using asList() Method

The asList() method of the Arrays class can be used to convert an array to ArrayList. This method returns a list which we can pass to the ArrayList constructor to convert the list to an ArrayList.

ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(fruits));

Here, arrayList will have all the elements of the fruits array.

Print the converted ArrayList

Using the println() method, you can print the newly-converted ArrayList.

System.out.println(arrayList);

The complete code for steps 2-4 looks like this:

String[] fruits = {"Apple", "Orange", "Banana"};
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(fruits));
System.out.println(arrayList);

To execute this code, compile the ArrayToArrayList.java file using the following command:

javac ArrayToArrayList.java

Then, run the file using the following command:

java ArrayToArrayList

Convert using addAll() Method

In Java, the addAll() method of the Collections class can be used to add all the elements of an array to an ArrayList. This method is used here instead of asList().

ArrayList<String> arrayList = new ArrayList<>();
Collections.addAll(arrayList, fruits);

Here, arrayList will also contain all the elements of the fruits array.

Print the converted ArrayList

Using the println() method, you can print the newly-converted ArrayList.

System.out.println(arrayList);

The complete code for steps 5-6 looks like this:

ArrayList<String> arrayList = new ArrayList<>();
Collections.addAll(arrayList, fruits);
System.out.println(arrayList);

To execute this code, compile the ArrayToArrayList.java file using the following command:

javac ArrayToArrayList.java

Then, run the file using the following command:

java ArrayToArrayList

Summary

In this lab, you learned how to convert an array to ArrayList in Java using the asList() and addAll() methods. With this skill, you can easily convert arrays to ArrayLists when required in your Java projects.

Other Java Tutorials you may like