ArrayListToArrayExample.java
Output
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); } } }
arrayList : [Ram, Dave, Peter, Julia, Akram]
Ram
Dave
Peter
Julia
Akram
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); } } }
arrayList : [Ram, Dave, Peter, Julia, Akram]
Ram
Dave
Peter
Julia
Akram
https://sites.google.com/site/javaee4321/java-collections/ArrayListDemoToArray.zip?attredirects=0&d=1
See also:
No comments:
Post a Comment