PUBLISHED ON: AUGUST 25, 2021
Array To ArrayList in Java
In this post, we are going to convert an array to ArrayList
. The ArrayList
is an implementation class of List
interface in Java that is used to store elements index-based while an array is used to store similar types of elements.
There can be a scenario where you are working with the collection of data and your data is stored into an array and you want to get it into ArrayList then you need to convert it.
Here, we are using asList()
method of Arrays
class that returns a list and then we can get ArrayList
from this list.
The addAll() method belongs to Collections
class and can be used to add array elements to the ArrayList.
Time for an Example:
Let's create an example to get ArrayList from array elements. Here, we are using asList()
method inside the constructor because ArrayList has one constructor to get the list as an argument.
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args){
String[] fruits = {"Apple", "Orange", "Banana"};
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(fruits));
System.out.println(arrayList);
}
}
Apple
Orange
Banana
[Apple, Orange, Banana]
Time for another Example:
Let's take another example to understand the array to ArrayList conversion. Here, we are using the addAll() method to add all the array elements to an ArrayList. See the example below.
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args){
String[] fruits = {"Apple", "Orange", "Banana"};
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
ArrayList<String> arrayList = new ArrayList<>();
Collections.addAll(arrayList, fruits);
System.out.println(arrayList);
}
}
Apple
Orange
Banana
[Apple, Orange, Banana]