3:13 pm - Thursday December 17, 3615

Java Program returns an array containing all of the elements in this list in proper sequence (from first to last element) using T[] toArray(T[] a) method

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

BACK

 

               The java.util.ArrayList.toArray(T[]) method returns an array containing all of the elements in this list in proper sequence (from first to last element).

Example Program


import java.util.ArrayList;

public class Sequence {
	public static void main(String[] args) {
     
   // create an empty array list with an initial capacity
   ArrayList<Integer> seq = new ArrayList<Integer>();

   // use add() method to add values in the list
   seq.add(10);
   seq.add(12);
   seq.add(31);
   seq.add(49);
	
   System.out.println("Printing elements of array1");

   // let us print all the elements available in list
   for (Integer number : seq) {
     System.out.println("Number = " + number);
   }  

   
   Integer list2[] = new Integer[seq.size()];
   list2 = seq.toArray(list2);

   System.out.println("Printing elements of array2");

   for (Integer number : list2) {
     System.out.println("Number = " + number);
   }
 }
}

Output:

Printing elements of array1

Number = 10

Number = 12

Number = 31

Number = 49

Printing elements of array2

Number = 10

Number = 12

Number = 31

Number = 49

Explanation:

  • 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.
  • If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the collection is set to null

Parameter:

  • 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.
  • If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the collection is set to null

Return Value:

This method returns an array containing the elements of the list.

Exception:

  • ArrayStoreException — If the runtime type of the specified array is not a supertype of the runtime type of every element in this list.
  • NullPointerException — If the specified array is null.

 

BACK

Filed in: Z-A All Java Codes

Comments are closed.