Convert an array to an ArrayList in Java
In the previous article, we saw how convert an ArrayList to an array with example. In this tutorial, we'll do the opposite: convert an ArrayList to an array.
1) Copy the array elements to the ArrayList
This method consists of going through the array elements and copying them one by one into an ArrayList.
import java.util.ArrayList;
public class ArraylistToTable {
public static void main(String[] args) {
ArrayListt = new ArrayList ();
String[] classes = {"Health classes" ,"architecture online classes",
"electrician classes"};
//Copy obj values to t
List< String> al = (ArrayList< String>) toArrayList(classes);
//Display
for(int i=0; i < al .size(); i++)
System.out.println(al.get(i));
}
static < T>List< T> toArrayList(T[] Array){
List< T>al = new ArrayList< T> ();
for(T obj: Table)
al.add(obj);
return al;
}
}
2) The Arrays.asList()
The Arrays.asList() converts to a single line.import java.util.ArrayList;Output:
import java.util.Arrays;
import java.util.List;
public class ArraylistToTable {
public static void main(String[] args) {
String[] card = {"visaCard" ,"MasterCard" , "AmericanExpress"};
ArrayListal = new ArrayList (Arrays.asList(card));
//Display
for(int i=0; i < al.size(); i++)
System.out.println(al.get(i));
}
}
visaCardAvoid using the type List because we'll have two problems:
MasterCard
AmericanExpress
- The size returned by asList() is fixed, if you remove or add elements, you have to do it in a new ArrayList() otherwise you'll have an exception; UnsupportedOperationException.
- The returned array is linked to the original array, if you modify the original array, the list will be modified too.
List l = Arrays.asList(card);Output
//Edit original array
card[0]="Neteller";
for(int i=0; i < l.size(); i++)
System.out.println(l.get(i));
Neteller
MasterCard
AmericanExpress
3) The Collections.AddAll()
Another way is equivalent to asList() is the use of Collections.AddAll(). This method is more efficient and faster and we can say that it is the best way to do the conversion to ArrayList.
import java.util.ArrayList;Output:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArraylistToTable {
public static void main(String[] args) {
Listal = new ArrayList ();
String[] titles = {"title1, title2, title3"};
Collections.addAll(al, titles);
//Display
for(int i=0; i < al.size(); i++)
System.out.println(al.get(i));
}
}
title1
title2
title3