Conversion of Array To ArrayList in Java is the top question in one of the most viewed and voted questions on StackOverflow. You can convert an array to ArrayList using the following ways.
- Using Arrays.asList() method: Simply pass the array in method.
- Collections.addAll() method: Create a new list and add array elements using this method to an existing list.
- Iteration method: Create a new list and add array elements with the help of for-loop.
Let’s Create ArrayList from array
For example, you have an array that is initialized like:
Elem[] array = {new Elem(1), new Elem(2), new Elem(3)};
And you want to convert this array into an object of the ArrayList class.
ArrayListarraylist = ???;
1. Arrays.asList() method
This is The Most Popular and Accepted Answer on stackoverflow.com.
new ArrayList<>(Arrays.asList(array))
Let’s see the example of it:-
import java.util.Arrays; import java.util.List; public class HelloTest { public static void main(String[] args) { String[] arr = {"a", "b", "c", "d", "e"}; //Method 1 Listlist = Arrays.asList(arr); System.out.println(list); } }
Output: [a, b, c, d, e]
Note: the size of the list returned from asList()
is fixed. if add or remove elements from the returned list, an UnsupportedOperationException
will be thrown.
2. Collections.addAll() method
It seems an extra step as an upper code. But it’s not, this ArrayList is not a fixed size. You can add more elements.
Collections.addAll(list, array);
Complete example code:
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class HelloTest { public static void main(String[] args) { String[] arr = {"a", "b", "c", "d", "e"}; //Method 2 Listlist = new ArrayList (); Collections.addAll(list, arr); System.out.println(list); } }
Output: [a, b, c, d, e]
3. Iteration method
Using a for-each loop and list add method. Loop will run for every element in the array and then adding into a list.
import java.util.ArrayList; import java.util.List; public class HelloTest { public static void main(String[] args) { String[] arr = {"a", "b", "c", "d", "e"}; //Method 3 Listlist = new ArrayList<>(); for(String text:arr) { list.add(text); } System.out.println(list); } }
Output: [a, b, c, d, e]
Do comment if you have any doubts and suggestions on this tutorial. If you know other methods to do it, then comment below, we will update them in this tutorial.
Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.15.1
Java version 11
All Java Array to Arraylis Example are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.