Wednesday, 25 July 2012

Convert ArrayList to Array in Java

This Java Example shows how to convert Java ArrayList object to an array using toArray method.


import java.util.ArrayList;
import java.util.List;

public class ConvertArrayListToArrayExample {

 public static void main(String[] args) {

  // create an ArrayList object

  List< string > list = new ArrayList< string >();

  // Add elements to the list

  list.add("India");
  list.add("Switzerland");
  list.add("Italy");
  list.add("France");

  System.out.println("ArrayList contains...");

  // display elements of ArrayList

  for (int index = 0; index < list.size(); index++)
   System.out.println(list.get(index));

  /**
   * Object[] toArray() - Returns an Object class array containing all of
   * the elements in this list in the correct order.Note that we can't
   * explicitly cast the returned array to some other class type.
   **/
  Object[] countries = list.toArray();

  System.out.println("Content of array countries=");

  for (Object c : countries) {
   System.out.println(c);
  }
  /**
   * Object[] toArray(Object[] a) - Returns an array containing all of the
   * elements in this list in the correct order; the runtime type of the
   * returned array is that of the specified array.
   **/

  String[] countries1 = list.toArray(new String[list.size()]);

  System.out.println("Content of array countries1=");

  for (String c : countries1) {
   System.out.println(c);
  }

 }
}


The output is:



ArrayList contains...
India
Switzerland
Italy
France
Content of array countries=
India
Switzerland
Italy
France
Content of array countries1=
India
Switzerland
Italy
France

No comments:

Post a Comment