PUBLISHED ON: JANUARY 28, 2021
Create an ArrayList From an Array in Java
In this tutorial, we will learn about how to create an ArrayList from an Array in Java. ArrayList belongs to java.util
package. ArrayList has a variable size and this characteristic makes it a better choice over arrays. Primarily there are three ways of doing this :
- By adding each element of the array to ArrayList explicitly.
- By using
Arrays.asList()
method.
- By using
Collections.addAll()
method
Example 1:
Creating an ArrayList from an Array by adding each element to an ArrayList from an Array.
import java.util.*;
public class StudyTonight
{
public static void main(String[] args)
{
ArrayList<String> courses= new ArrayList<String>();
String array[] = {"Java","Python","C","C++"};
for(int i =0;i<array.length;i++)
{
courses.add(array[i]);
}
for(String course: courses)
{
System.out.println(course);
}
}
}
Java
Python
C
C++
Example: Creating an ArrayList from an Array using Arrays.asList()
method.
In this example asList()
method from an Arrays
class will convert the given array to an ArrayList.
import java.util.*;
public class StudyTonight
{
public static void main(String[] args)
{
String courses[]={"Java", "Python", "Android", "Web"};
ArrayList<String> courseList= new ArrayList<String>(Arrays.asList(courses));
for (String course: courseList)
{
System.out.println(course);
}
}
}
Java
Python
Android
Web
Example: Creating an ArrayList from an Array using Collections.addAll()
method.
In this example, addAll()
method from the Collections
class will convert Arrays to Arraylist. We pass two parameters to the addAll method i.e. ArrayList and array.
import java.util.*;
public class StudyTonight
{
public static void main(String[] args)
{
String array[]={"C", "C++", "Java", "Python"};
ArrayList<String> courses= new ArrayList<String>();
Collections.addAll(courses, array);
for (String course: courses)
{
System.out.println(course);
}
}
}
C
C++
Java
Python
Conclusion:
ArrayList has a variable size that's why it is useful to convert Arrays to ArrayList. We can that using three ways: by adding each element of the array to ArrayList explicitly, by using Arrays.asList()
method, and by using Collections.addAll()
method