8:41 pm - Thursday April 27, 2017

Java Program returns an array containing all of the elements in this collection using Object[] toArray() 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

 

Returns an array containing all of the elements in this collection. If the collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

Example Program


import java.util.ArrayList;

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

   // use add() method to add values in the list
   ao.add(20);
   ao.add(40);
   ao.add(10);
   ao.add(15);
   ao.add(25);
	
   // let us print all the elements available in list
   for (Integer number : ao) {
     System.out.println("Number = " + number);
   }  
	
   Object[] ob = ao.toArray();

   System.out.println("Printing elements from first to last:");
   for (Object value : ob) {
     System.out.println("Number = " + value);
   }
 }
}

Output:

Number = 20

Number = 40

Number = 10

Number = 15

Number = 25

Printing elements from first to last:

Number = 20

Number = 40

Number = 10

Number = 15

Number = 25

Explanation:

The java.util.ArrayList.toArray() method returns an array containing all of the elements in this list in proper sequence (from first to last element).This acts as bridge between array-based and collection-based APIs.

Parameter:Na

Return Value:

This method returns an array containing all of the elements in this list in proper sequence.

Exception:Na

Filed in: Z-A All Java Codes

Comments are closed.