Copy all elements of ArrayList to an Object Array in Java

Java 8Object Oriented ProgrammingProgramming

All the elements of an ArrayList can be copied into an Object Array using the method java.util.ArrayList.toArray(). This method does not have any parameters and it returns an Object Array that contains all the elements of the ArrayList copied in the correct order.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List<String> aList = new ArrayList<String>();
      aList.add("Nathan");
      aList.add("John");
      aList.add("Susan");
      aList.add("Betty");
      aList.add("Peter");
      Object[] objArr = aList.toArray();
      System.out.println("The array elements are: ");
      for (Object i : objArr) {
         System.out.println(i);
      }
   }
}

Output

The array elements are:
Nathan
John
Susan
Betty
Peter

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements to this ArrayList. A code snippet which demonstrates this is as follows −

List<String> aList = new ArrayList<String>();
aList.add("Nathan");
aList.add("John");
aList.add("Susan");
aList.add("Betty");
aList.add("Peter");

The method ArrayList.toArray() is used to copy all the elements of the ArrayList into an Object Array. Then the Object Array elements are displayed using a for loop. A code snippet which demonstrates this is as follows −

Object[] objArr = aList.toArray();
System.out.println("The array elements are: ");
for (Object i : objArr) {
   System.out.println(i);
}
raja
Published on 10-Jan-2019 09:23:54
Advertisements