Java Reference
In-Depth Information
Converting an ArrayList/Vector to an Array
An
ArrayList
can be used when the number of elements in the list is not precisely known. Once the number of elements
in the list is fixed, you may want to convert an
ArrayList
to an array. You may do this for one of the following reasons:
ArrayList
. For example, you
may need to pass an array to a method, but you have data stored in an
ArrayList
.
•
The program semantics may require you to use an array, not an
•
You may want to store user inputs in an array. However, you do not know the number of values
the user will input. In such a case, you can store values in an
ArrayList
while accepting input
from the user. At the end, you can convert the
ArrayList
to an array.
ArrayList
elements. If you have an
ArrayList
and you want to access the elements multiple times, you may want to convert the
ArrayList
to an array for better performance.
The
ArrayList
class has an overloaded method named
toArray()
:
•
Accessing array elements is faster than accessing
•
Object[ ]
toArray( )
•
The first method returns the elements of
ArrayList
as an array of
Object
. The second method takes an array of
any type as argument. All
ArrayList
elements are copied to the passed array if there is enough space and the same
array is returned. If there is not enough space in the passed array, a new array is created. The type of new array is the
same as the passed array. The length of the new array is equal to the size of
ArrayList
. Listing 15-15 shows how to
convert an
ArrayList
to an array.
<T> T[ ]
toArray(T[ ] a)
Listing 15-15.
An ArrayList to an Array Conversion
// ArrayListToArray.java
package com.jdojo.array;
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayListToArray {
public static void main(String[] args){
ArrayList<String> al = new ArrayList<String>();
al.add("cat");
al.add("dog");
al.add("rat");
// Print the content of arrayList
System.out.println("ArrayList:" + al);
// Create an array of teh same length as teh ArrayList
String[] s1 = new String[al.size()];
// Copy the ArrayList elements to teh array
String[] s2 = al.toArray(s1);