Friday 1 August 2014

convert List to Integer array in Java

By using toArray method, List<Integer> is converted to integer array.

public <T> T[] toArray(T[] a)
Returns an array containing all of the elements in this list in proper sequence, the run time type of the returned array is that of the specified array.

Example
import java.util.*;

class LinkedListSpecificArray{
 public static void main(String args[]){
  LinkedList<Integer> myList;
  myList = new LinkedList<> ();
  
  Integer myArray[];
  Integer retArray[];
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(123);
  myList.add(321);
  myList.add(456);
  
  int size = myList.size();
  
  myArray = new Integer[size];
  retArray = new Integer[size];
  
  retArray = myList.toArray(myArray);
  
  System.out.println("Elements in the list are");
  System.out.println(myList);
  
  System.out.println("Elements in myArray are");
  for(int i: myArray)
   System.out.print(i +" ");
   
  System.out.println("\nElements in the retArray are");
  for(int i: retArray)
   System.out.print(i +" "); 
 }
}

Output
Elements in the list are
[10, 123, 321, 456]
Elements in myArray are
10 123 321 456
Elements in the retArray are
10 123 321 456





                                                             Home

No comments:

Post a Comment