Java - Array and ArrayList/Vector

Introduction

The ArrayList class has an overloaded method named toArray():

Object[ ]         toArray( )
<T> T[ ]          toArray(T[ ] a)

The first method returns the elements of ArrayList as an array of Object.

The second method takes an array of any type as argument.

The following code shows how to convert an ArrayList to an array.

Demo

import java.util.ArrayList;
import java.util.Arrays;

public class Main {
  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 the ArrayList
    String[] s1 = new String[al.size()];

    // Copy the ArrayList elements to the array
    String[] s2 = al.toArray(s1);

    // s1 has enough space to copy all ArrayList elements.
    // al.toArray(s1) returns s1 itself
    System.out.println("s1 == s2:" + (s1 == s2));
    System.out.println("s1:" + Arrays.toString(s1));
    System.out.println("s2:" + Arrays.toString(s2));

    // Create an array of string with 1 element.
    s1 = new String[1];
    s1[0] = "hello"; // Store hello in first element

    // Copy ArrayList to the array s1
    s2 = al.toArray(s1);// w ww . ja v  a  2 s .c  om

    System.out.println("s1 == s2:" + (s1 == s2));
    System.out.println("s1:" + Arrays.toString(s1));
    System.out.println("s2:" + Arrays.toString(s2));
  }
}

Result