» » » Convert arraylist to array in java with example program

  • Inoder to convert arraylist to array normally we will try to iterate arraylist using loop and get each element and put it in an array.
  • But you know we have a predefined method in arraylist which convert list to array of elements in sequence order.
  • toArray() method inside arraylist class.



  1. public <T> T[] toArray(T[] a) {  }



  •  Lets see a java program on how to convert arraylist to array.

 Program #1: Java example program to covert arraylist to array using toArray() method


  1. package arraysinterview;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4.  
  5. public class ArrayListTOArray {
  6.  
  7.     public static void main(String[] args) {
  8.         List<String> list = new ArrayList<String>();
  9.         
  10.         list.add("array");
  11.         list.add("arraylist");
  12.         list.add("convertion");
  13.         list.add("javaprogram");
  14.         
  15.         String [] str = list.toArray(new String[list.size()]);
  16.         
  17.         for (int i = 0; i < str.length; i++) {
  18.             System.out.println(str[i]);
  19.         }
  20.  
  21.     }
  22.  
  23. }

Output:
  1. array
  2. arraylist
  3. convertion
  4. javaprogram

Program #2: Java example program to covert Integer arraylist to int array using toArray() method

  •  In this case toArray() method gives Integer array so we need to convert again Integer array to int array.



  1. package arraysinterview;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4.  
  5. public class ArrayListTOArray {
  6.  
  7.  public static void main(String[] args) {
  8.         List<Integer> list = new ArrayList<Integer>();
  9.         
  10.         list.add(10);
  11.         list.add(20);
  12.         list.add(30);
  13.         list.add(40);
  14.         list.add(50);
  15.         
  16.         Object[] integers = list.toArray();
  17.         
  18.         int[] intarray = new int[integers.length];
  19.         int i = 0;
  20.         for (Object n : integers) {
  21.             intarray[i++] = (Integer) n;
  22.             System.out.println(i);
  23.         }
  24.  
  25.     }
  26.  
  27. }



Output:
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5



Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu