Friday, 10 October 2014

Java : Collection Framework : ArrayList (Convert to Array Object)
























Click here to watch in Youtube : https://www.youtube.com/watch?v=1s_oAM0_SVs

ArrayListToArrayExample.java
import java.util.ArrayList;

/*
 * Example of toArray(T[] a) method
 */
public class ArrayListToArrayExample
{

    public static void main(String[] args)
    {
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("Ram");
        arrayList.add("Dave");
        arrayList.add("Peter");
        arrayList.add("Julia");
        arrayList.add("Akram");

        System.out.println("ArrayList : " + arrayList + "\n");

        String[] strArray = new String[arrayList.size()];

        /*
         * arrayList elements will be copied to StrArray
         */

        arrayList.toArray(strArray);

        for (String name : strArray)
        {
            System.out.println(name);
        }

    }

}

Output
arrayList : [Ram, Dave, Peter, Julia, Akram]

Ram
Dave
Peter
Julia
Akram

ArrayListToObjArrayExample.java
import java.util.ArrayList;

/*
 * Example of toArray() method
 */
public class ArrayListToObjArrayExample
{

    public static void main( String[] args )
    {
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("Ram");
        arrayList.add("Dave");
        arrayList.add("Peter");
        arrayList.add("Julia");
        arrayList.add("Akram");

        System.out.println("arrayList : " + arrayList + "\n");

        /*
         * Returns an array containing all of the elements in this list in
         * proper sequence (from first to last element).
         */

        Object[] objArray = arrayList.toArray();

        for( Object object : objArray )
        {
            String name = (String) object;
            System.out.println(name);
        }

    }

}

Output
arrayList : [Ram, Dave, Peter, Julia, Akram]

Ram
Dave
Peter
Julia
Akram

To Download ArrayListDemoToArray Project Click the below link

https://sites.google.com/site/javaee4321/java-collections/ArrayListDemoToArray.zip?attredirects=0&d=1

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Post a Comment

    Google+ Followers

    Google+ Badge