Java ArrayList.toArray() Method

 Posted On  | Yashwant Chavan 

In this tutorial you will learn about Java ArrayList.toArray() method. ArrayList.toArray() method converts ArrayList to an object Array which contains all the elements of the list in proper sequence.

syntax

Returns an array containing all of the elements in this list in proper sequence.

Object[] java.util.ArrayList.toArray()

Return

It returns an Object Array. This method creates a new array that contains all the elements of the List.

Java ArrayList.toArray() example

Refer below steps

  • Constructs an empty ArrayList with an initial capacity using new ArrayList<String>().
  • Add some elements in colors ArrayList using add() method.
  • Print List elements using for loop.
  • Convert ArrayList to Object Array using toArray() method (colors.toArray()).
  • Print all elements of newly constructed Object Array using for loop.
package com.technicalkeeda.app;

import java.util.ArrayList;

public class ArrayListToArray {
    public static void main(String[] args) {

        ArrayList <String> colors = new ArrayList <String> ();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");
        colors.add("Pink");
        colors.add("Black");
        colors.add("White");

        for (String color: colors) {
            System.out.println("ArrayList Element :- " + color);
        }

        System.out.println();

        Object[] colorArray = colors.toArray();
        for (Object color: colorArray) {
            System.out.println("Array Element :- " + color);
        }

    }
}

Output

ArrayList Element :- Red
ArrayList Element :- Green
ArrayList Element :- Blue
ArrayList Element :- Pink
ArrayList Element :- Black
ArrayList Element :- White

Array Element :- Red
Array Element :- Green
Array Element :- Blue
Array Element :- Pink
Array Element :- Black
Array Element :- White


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0255 seconds.