Java News Tips Software
Java News Tips Software | Contact | Facebook | Twitter RSS

[Java Tips] Add Array into a List and convert a List into an Array

With Java, putting contents of an Array into a new List object or adding into an existing List object can be achieved easily using a for() loop; just by going through each and every element in array and adding to List one at a time. But that is not needed. Java has provided a method to achieve that easily; just with one method call. Following code snippet shows how.

//import java.util.List;
//import java.util.Arrays;
String[] array = {"one", "two", "three"};
List newListObject = Arrays.asList(array);

//adding to existing List
String[] newArray = {"four", "five"};

List all = new ArrayList();

Also creating a new Array object using an existing List object can be done using another for() loop; by creating a new Array object with a size matching to list size and adding each on at a time. But for this requirement, there are a set of methods.

List list = new ArrayList();

Object[] array1 = list.toArray(); //1
String[] array2 = (String[])list.toArray(new String[0]); //2

String[] array3 = new String[2];
list.toArray(array3); //3

With Line #1, returned array is of Object type, while #2 returns a new array object of String type.
Line #3 uses the same method used in #2, but in this case we have provided an array object with the same size as the list. Because of that in line #3, the provided array object is populated with list elements.

Labels: ,


  1. i am having an list.. i want to convert it to an array of objects how to do that?
  2. Hi Sandy,

    The article explains how to convert a list into an array. Hasn't it solve your problem? Can you details your issue?
  3. Anonymous Anonymous on January 21, 2009 5:15 PM  
    This comment has been removed by a blog administrator.
  4. how to connect a string array to list? string array consists of string[] week =={"week1","week2","week3","week4",...."week51'};

    how to connect the given array to list
  5. Anonymous Anonymous on April 05, 2010 2:34 PM  
    this code work correctly with String try this example:

    double[] array = {1, 2, 3};
    List newListObject = Arrays.asList(array);
  6. great..its work.Thanks
  7. nyc job.
  8. hi sandy. this worthed..thanks
  9. Hi guys,

    I am working on an android app which has to display a list of objects, say Books.
    The application receives from the server a jagged array with IDs and Titles.

    Does anyone know how to separate IDs from Titles into 2 ArrayLists?

    I need Array Lists to be able to display them in the Adnroid ListView.

    Thanks alot.
  10. Anonymous Anonymous on January 21, 2014 6:51 AM  
    This comment has been removed by a blog administrator.
Page Views :
Email :
Select Month:
Free counter and web stats