Monday 7 May 2012

Java ArrayList toArray Example

ArrayList class toArray method example. This example shows you how to use toArray method. ArrayList class toArray method example.toArray(T[] a) Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list. Here is the code /** * @ # toArray1.java * A class repersenting use to toArray method of ArrayList class in java.util package */ import java.util.*; public class ToArray1 { public static void main(String args[]) { List arrlist = new ArrayList(); int i = 0; String str = "Rose"; //Add the specified element to the end of this list. arrlist.add(i); arrlist.add(str); arrlist.add("India"); System.out.println("arrlist = " + arrlist); Object arr[] = {"Komal", "Choudhary"}; System.out.println("Elements of arr "); for (int a = 0; a < arr.length; a++) { System.out.println(arr[a].toString()); } // The existing elements in arr are replaced with the // contents of the ArrayList. arr = arrlist.toArray(arr); System.out.println("\nElements of arr "); for (int a = 0; a < arr.length; a++) { System.out.println(arr[a].toString()); } } } Output: -------------------------- arrlist = [0, Rose, India] Elements of arr Komal Choudhary Elements of arr 0 Rose India

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...